注解方式的AOP配置
1,首先切面类
package com.ming.anno;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component("myAspect")
@Aspect//告诉Spring容器切面类
public class MyAspect {
@Before("execution(* com.ming.anno.*.*(..))")//正常的xml配置是<aop:before method="before" pointcut="execution(* com.ming.aop.*.*(..))"></aop:before>可以对比注释
public void before(){
System.out.println("前置增强...");
}
}
2.目标对象
package com.ming.anno;
import org.springframework.stereotype.Component;
@Component("Target")//注入实现类
public class Target implements TargetInterface {
public void save() {
System.out.printf("save running...");
}
}
3.接口类
不用注入
package com.ming.anno;
public interface TargetInterface {
public void save();
}
4.applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="com.ming.anno"/>
<!--Aop代理-->
<aop:aspectj-autoproxy/>
//没错只需要加入这两句话
</beans>
5.测试类
package com.ming.Test;
import com.ming.anno.TargetInterface;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AnnoAopTest {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
6.运行结果
前置增强...
save running...
Process finished with exit code 0