spring实现aop的方式有一下几种
1、基于代理的AOP
2、纯简单java对象切面
3、@Aspect注解形式的
4、注入形式的Aspcet切面
<aop:aspectj-autoproxy />有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy poxy-target-class="true"/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。
下面是用@aspect注解形式实现的,首先是导入一些的jar包
切面的代码
@Component @Aspect public class Advice { @Before("init()")//通知 public void log(){ System.out.println("before do..."); } @Pointcut("execution(* service.*.*(..))")//方法切入点,execution为执行的意思,*代表任意返回值,然后是包名,.*意思是包下面的所有子包。(..)代表各种方法.
public void init(){ } }
实现类
@Component("serviceImpl") public class ServiceImpl implements Service { @Override public void saySomething() { System.out.println("do.."); } }
spring的配置文件中添加
<context:annotation-config></context:annotation-config> <context:component-scan base-package="service,advice"></context:component-scan> <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring
在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了
测试代码
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac = new ClassPathXmlApplicationContext("service/bean.xml"); Service ser = (Service) ac.getBean("serviceImpl"); ser.saySomething(); } }
结果就是在输出do..之前输出了before do...
实际应用中可以用来实现日志功能
你把
<aop:aspectj-autoproxy/>
也放在了application.xml中了。可能是springmvc的bug吧。你把
<aop:aspectj-autoproxy/>