spring在bean获得@autowired之前将字段注入bean

roqulrg3  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(396)

在spring中,是否有一种机制或监听器来检测用特定注解注解的bean何时被获取 @Autowired 在上面运行一些自定义逻辑?类似于什么 @ConfigurationProperties 在自动连线之前自动注入字段。
我有一个需求,需要将值注入到用 @ExampleAnnotation 在它们被示例化之前。理想情况下,在这个听众中,我会:
询问当前示例化的bean是否用 @ExampleAnnotation 如果不是,返回。如果是,我将使用反射从这个bean中获取字段的名称,并使用存储库填充它们。
这样的事情可能吗?

rsl1atfo

rsl1atfo1#

您可以通过以下代码实现:

@Component
class MyBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      // Every spring bean will visit here

      // Check for superclasses or interfaces
      if (bean instanceof MyBean) {
        // do your custom logic here
        bean.setXyz(abc);
        return bean;
      }
      // Or check for annotation using applicationContext
      MyAnnotation myAnnotation = this.applicationContext.findAnnotationOnBean(beanName, MyAnnotation.class);
      if (myAnnotation != null) {
        // do your custom logic here
        bean.setXyz(myAnnotation.getAbc());
        return bean;
      }
      return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      this.applicationContext = applicationContext;
    }

    // Optional part. If you want to use Autowired inside BeanPostProcessors 
    // you can use Lazy annotation. Otherwise they may skip bean processing
    @Lazy
    @Autowired
    public MyBeanPostProcessor(MyLazyAutowiredBean myLazyAutowiredBean) {
    }
}
8ljdwjyq

8ljdwjyq2#

我想如果它和 ConfigurationProperties ,然后上课 ConfigurationPropertiesBindingPostProcessor 将属性绑定到bean的。它实现了 BeanPostProcessor 并且在 postProcessBeforeInitialization 方法。此方法具有以下javadocs:
“在任何beaninitialization回调之前,将此beanpostprocessor应用于给定的新bean示例(如initializingbean的AfterPropertiesStor自定义初始化方法)。该bean将已被属性值填充。返回的bean示例可能是原始示例的 Package 器。“

yhuiod9q

yhuiod9q3#

一种可能的解决方案是编写自定义setter并用@autowired对其进行注解,如下所示:

@Autowired
public void setExample(Example example)
{

    // Do your stuff here.

    this.example = example;
}

但是,我不推荐这种在自动连接之前修改bean的做法,因为这会导致代码可维护性差,而且对于其他需要处理您的代码的人来说,这可能是违反直觉的。

相关问题