有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在插入新bean时如何更新现有的自动连接属性?

我们有自动连接特定类型bean的组件类:

@Component
public class MyComponent {
    @Autowire
    public IValidators[] validators;
}

我们的应用程序允许创建在运行时编译并使用ScriptFactoryPostProcessor向Spring注册的Groovy类:

ConstructorArgumentValues args = new ConstructorArgumentValues();
args.addGenericArgumentValue(groovySourceLocation); //location is on the file system
RootBeanDefinition def = new RootBeanDefinition(GroovyScriptFactory.class, args, null);
BeanDefinitionRegistry r = (BeanDefinitionRegistry) this.applicationContext.getBeanFactory();
r.registerBeanDefinition(beanName, def); //beanName is the same as the class name

//scriptFactoryPostProcessor is autowired into class from applicationConfig
scriptFactoryPostProcessor.postProcessBeforeInstantiation(GroovyScriptFactory.class, beanName);

groovy bean是正确创建的,因为我可以通过bean名称或类型从applicationContext检索它。但是组件已经自动连接的属性没有添加的bean。当groovy类实现IValidator时,我希望任何自动连接IValidator类型的组件类都能用添加到集合中的新groovy bean进行更新。我该怎么做

更新

通过查看源代码,我看不出Spring支持我的期望。我最后的希望是,我可以请求某种类型的依赖bean(类似于getDependentBeans(String beanName)),但它不存在,而且从外观上看,Spring不跟踪基于类型的依赖关系


共 (2) 个答案

  1. # 1 楼答案

    真是个有趣的问题。最简单的方法是:制作MyComponent原型,并在每次需要时创建新实例。通过这种方式,Spring将对最近的IValidator实例列表执行自动连接。考虑^ {CD3}}。

    不那么优雅的方法是建立一个工厂(notaFactoryBean),它将根据需要检索所有实现IValidator的bean,并在需要时直接调用这个工厂。当然,完全不是在春天的气氛中

    其他方法更麻烦,也更容易出错。您可以创建自己的后处理器,将新发现的IValidator添加到需要所有类列表的所有类中。您还可以开发自己的List<IValidator>实现,每次请求时都会查找ApplicationContext,这有点困难,尤其是考虑到并发性时

    最后还有一个复合设计模式:只有一个IValidator将所有调用委托给在^{中手动发现的目标IValidator列表