SpringAOP及自定义后置处理器的示例分享

书欣 Spring 发布时间:2023-01-04 10:55:04 阅读数:8051 1
下文笔者讲述Spring中AOP及后置处理器的示例分享,如下所示
实现思路:
    1.引入相应的依赖
	2.使用 @Aspect注解和@Pointcut注解
	  即可为指定方法添加增强器
例:
AOP示例分享
添加aspectj依赖

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
	<groupId>org.aspectj</groupId>
	<artifactId>aspectjweaver</artifactId>
	<version>1.9.4</version>
</dependency>
  
1.接口
public interface UserService {
    void query();
}
 
2.接口实现
@Component
public class UserServiceImpl implements UserService {

    public void query(){
        System.out.println("spring -----init -----");
    }
} 

//Spring AOP示例

3.切面

@Component
@Aspect
public class AopAspect {
    @Pointcut("execution(* com.java265.spring.aop..*.*(..))")
    public void pointCut(){
        System.out.println("oap pointCut-----------");
    }

    @Before("pointCut()")
    public void before(){
        System.out.println("oap before -----------");
    }

    @After("execution(* com.java265.spring.aop..*.*(..))")
    public void after(){
        System.out.println("oap after -----------");
    }
} 

4.配置类
@Configuration
@ComponentScan("com.java265.spring.aop")
@EnableAspectJAutoProxy
public class Appconfig {

}
 
5.测试
public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Appconfig.class);
        //Spring容器就是一个ConcurrentHashMap
        //代理对象不是在getBean的事后代理的,代理是在init初始化的时候完成了
        ac.getBean(UserService.class).query();
    }
}
 
6、运行结果

oap before -----------
spring -----init -----
oap after -----------
 

二、自定义后置处理器

BeanPostProcessor
  该接口定义了两个方法
  在bean实例化之后放到我们的容器之前和之后去执行

方法的返回值为一个object,这个object呢就是我们存在于容器的对象了
例
接口和实现类与上面一致

3.定义动态代理
public class UserHandler implements InvocationHandler {
    private Object object;
    public UserHandler(Object object){
        this.object = object;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("UserHandler -------------------");
        return method.invoke(object,args);
    }
} 

4.自定义AOP后置处理器
@Component
public class UserPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("UserServiceImpl"))
            bean = Proxy.newProxyInstance
                (UserPostProcessor.class.getClassLoader(),new Class[]{UserService.class},new UserHandler(bean));
        return bean;
    }
} 

5.配置类
@Configuration
@ComponentScan("com.java265.spring.aop")
//@EnableAspectJAutoProxy
public class Appconfig {
} 

6.测试类
public class Test {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Appconfig.class);
        //Spring容器就是一个ConcurrentHashMap
        //代理对象不是在getBean的事后代理的,代理是在init初始化的时候完成了
        ac.getBean(UserService.class).query();
    }
}

 
7.运行结果
UserHandler -------------------
spring -----init -----
 
如果想使用标签进行AOP控制,可以自定义标签
第4步将@Component注释掉,变为:

//@Component
public class UserPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("UserServiceImpl"))
            bean = Proxy.newProxyInstance
                (UserPostProcessor.class.getClassLoader(),new Class[]{UserService.class},new UserHandler(bean));
        return bean;
    }
}
 
然后自定义标签
@Import(UserPostProcessor.class)
@Retention(RetentionPolicy.Runtime)
public @interface EnableUser {
}
 
5.第5步配置类注入自定义标签
@Configuration
@ComponentScan("com.java265.spring.aop")
@EnableUser
public class Appconfig {
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Spring/202301/5285.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者