zoukankan      html  css  js  c++  java
  • 使用AspectJ提供的注解方式实现aop

    spring实现aop的方式有一下几种       

            1、基于代理的AOP

            2、纯简单java对象切面

            3、@Aspect注解形式的

            4、注入形式的Aspcet切面

    下面是用@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...

    实际应用中可以用来实现日志功能

  • 相关阅读:
    十天冲刺之三
    设计模式-模板方法模式
    设计模式-观察者模式
    设计模式-迭代子模式
    设计模式-责任链模式
    设计模式-门面模式
    1395. Count Number of Teams
    747. Largest Number At Least Twice of Others
    1160. Find Words That Can Be Formed by Characters
    1539. Kth Missing Positive Number
  • 原文地址:https://www.cnblogs.com/yeming/p/5444959.html
Copyright © 2011-2022 走看看