spring-基于xml的aop开发-快速入门
1.導入aop的相關坐標
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.9.RELEASE</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.13</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.5.RELEASE</version></dependency>如果使用spring原生的aop進行織入,則導入spring-context就夠了(因為spirng-context包含spring-aop),但是spring官方推薦使用第三方小框架aspectjweaver進行織入(spring不排斥任何優秀的框架)
2.創建目標接口和目標類
public interface TargetInterface {public void save(); } public class Target implements TargetInterface{public void save() {System.out.println("save running....");} }3.創建切面類
public class MyAspect {public void before(){System.out.println("前置增強。。。");}}4.將目標和切面類的對象創建權交給spring
注意:這一步只是把目標對象類和切面對象類交給spring管理,現在spring還只認為你這只是普通類,所有引入了第五步操作。
5.在applicationContext.xml中配置織入關系
aop:aspect標簽配置切面,那切面是誰呢,使用ref引入切面的唯一標識id,此時這一步配置之后,第二個bean標簽引入的類就真正成為了切面類
aop:before:通知的類型,method引入切面中的增強方法;ponintcut:切點表達式(最后講)
6.測試代碼
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class AopTest {@Autowired@Qualifier("target")private TargetInterface target;@Testpublic void test1(){target.save();} }結果:
execution
public:修飾符(可以省略)
void 返回值類型
com.hao.aop:包名
Target:類名
save(參數):方法名
execution(void com.hao.aop.Target.*(…)) :表示Target類下所有無返回值的方法都會被增強
execution( * com.hao.aop.. (. .):表示任意類的任意方法都可以
execution(* com.hao.aop. . *. *(. .):表示aop包下的任意類方法或者任意子包下的任意類方法
總結
以上是生活随笔為你收集整理的spring-基于xml的aop开发-快速入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring-aop相关概念
- 下一篇: spring-xml实现aop-通知的种