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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix