Bean的后置处理器----BeanPostProcessor

Bean的后置处理器在bean的生命周期中扮演一个十分重要的角色。

生命周期:

1.生成BeanDefinition

2.合并BeanDefinition

3.加载类

4.实例化前

5.推断构造方法

6.实例化

7.BeanDefinition的后置处理

8.填充属性

。。。。

BeanPostProcessor 是一个接口,他有两个实现类,可以将他看成一个AOP操作。在对象变成bean之间进行干涉,会先执行postProcessBeforeInitialization,再postProcessAfterInitialization
public interface BeanPostProcessor {
    Object postProcessBeforeInitialization(Object var1, String var2) throws BeansException;

    Object postProcessAfterInitialization(Object var1, String var2) throws BeansException;
}
复制代码
public class WxyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }
}
复制代码

==========后置处理器的有趣实战==================

添加注解abc

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface abc {

    String value();
}
public class User {
    @abc("xxxxwxy")
    private String name;

    public void test(){
        System.out.println(name);
    }
}
    public static void main(String[] args) {


        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(Config.class);
        User user = annotationConfigApplicationContext.getBean("user",User.class);
        user.test();

    }

 

 可以看出来此时的name还是没有值的。因为@wxy注解还没有生效

 

对后置处理器的实现类进行更改,对name值进行注入。

复制代码
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        for (Field field : clazz.getDeclaredFields()){
            if (field.isAnnotationPresent(abc.class)){
                abc abcAnnotation = field.getAnnotation(abc.class);
                String value = abcAnnotation.value();
                field.setAccessible(true);
                try {
                    field.set(bean,value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return bean;
    }
复制代码

 

posted @   WXY_WXY  阅读(105)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示