码迷,mamicode.com
首页 > 编程语言 > 详细

使用spring的注解方式实现aop

时间:2016-04-29 07:04:12      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

首先是导入一些的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...

使用spring的注解方式实现aop

标签:

原文地址:http://www.cnblogs.com/yeming/p/5444959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!