首页 > 编程语言 > 详细

Spring-AOP-完全注解方式(了解)

时间:2020-08-18 08:07:40      阅读:70      评论:0      收藏:0      [点我收藏+]

(1)配置类

package com.orzjiangxiaoyu.aop.test2;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author orz
 * @create 2020-08-17 21:42
 */
@Configuration
@ComponentScan(basePackages = {"com.orzjiangxiaoyu.aop"})//开启组件扫面
@EnableAspectJAutoProxy(proxyTargetClass = true)//开启Aspect生成代理对象
public class ConfigAop {
}

(2)被增强类

package com.orzjiangxiaoyu.aop.test2;

import org.springframework.stereotype.Component;

/**
 * @author orz
 * @create 2020-08-17 22:53
 */
@Component
public class Person {
    public void add()
    {
        System.out.println("Person add...");
    }
}

(3)增强类

package com.orzjiangxiaoyu.aop.test2;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author orz
 * @create 2020-08-17 22:54
 */
@Component
@Aspect
@Order(5)
public class PersonPonxy1 {
    @Before(value = "execution(* com.orzjiangxiaoyu.aop.test2.Person.add() )")
    public void before()
    {
        System.out.println("PersonPonxy1 add...");
    }
}
package com.orzjiangxiaoyu.aop.test2;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author orz
 * @create 2020-08-17 22:56
 */
@Component
@Aspect
@Order(1)
public class PersonPonxy2 {
    @Before(value = "execution(* com.orzjiangxiaoyu.aop.test2.Person.add() )")
    public void before()
    {
        System.out.println("PersonPonxy2 add...");
    }

}

(4)测试

package com.orzjiangxiaoyu.aop.test2;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author orz
 * @create 2020-08-17 20:03
 */
public class Test1 {
   
    @Test
    public void test2()
    {
        ApplicationContext context=new AnnotationConfigApplicationContext(ConfigAop.class);
        Person person = context.getBean("person",Person.class);
        person.add();
    }
}

(5)结果

PersonPonxy2 add...
PersonPonxy1 add...
Person add...

 

Spring-AOP-完全注解方式(了解)

原文:https://www.cnblogs.com/orzjiangxiaoyu/p/13520825.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!