【问题标题】:How to instantiate Spring managed beans at runtime?如何在运行时实例化 Spring 托管 bean?
【发布时间】:2015-01-07 00:55:20
【问题描述】:

我坚持从纯 Java 到 Spring 的简单重构。应用程序有一个“容器”对象,它在运行时实例化它的部分。让我用代码解释一下:

public class Container {
    private List<RuntimeBean> runtimeBeans = new ArrayList<RuntimeBean>();

    public void load() {
        // repeated several times depending on external data/environment
        RuntimeBean beanRuntime = createRuntimeBean();
        runtimeBeans.add(beanRuntime);
    }

    public RuntimeBean createRuntimeBean() {
         // should create bean which internally can have some 
         // spring annotations or in other words
         // should be managed by spring
    }
}

基本上,在加载容器期间,容器会要求一些外部系统向他提供有关每个 RuntimeBean 的数量和配置的信息,然后它会根据给定的规范创建 bean。

问题是:通常我们在Spring做的时候

ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfiguration.class);
Container container = (Container) context.getBean("container");

我们的对象已完全配置并注入了所有依赖项。但在我的情况下,我必须在执行 load() 方法后实例化一些也需要依赖注入的对象。
我怎样才能做到这一点?

我正在使用基于 Java 的配置。我已经尝试为RuntimeBeans 制作工厂:

public class BeanRuntimeFactory {

    @Bean
    public RuntimeBean createRuntimeBean() {
        return new RuntimeBean();
    }
}

期待@Bean 在所谓的“精简”模式下工作。 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html 不幸的是,我发现简单地执行 new RuntimeBean(); 没有区别; 这是一个类似问题的帖子:How to get beans created by FactoryBean spring managed?

还有http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Configurable.html,但在我的情况下它看起来像一把锤子。

我还尝试了 ApplicationContext.getBean("runtimeBean", args) 其中 runtimeBean 具有“原型”范围,但 getBean 是一个糟糕的解决方案。


更新 1

更具体地说,我正在尝试重构这个类: https://github.com/apache/lucene-solr/blob/trunk/solr/core/src/java/org/apache/solr/core/CoreContainer.java @see #load() 方法并找到“return create(cd, false);”

更新 2

我在 Spring 文档中发现了一个非常有趣的东西,叫做“查找方法注入”: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-lookup-method-injection

还有一张有趣的 jira 票 https://jira.spring.io/browse/SPR-5192,Phil Webb 说 https://jira.spring.io/browse/SPR-5192?focusedCommentId=86051&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-86051 应该在这里使用 javax.inject.Provider(这让我想起了 Guice)。

更新 3

还有http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.html

更新 4

所有这些“查找”方法的问题是它们不支持传递任何参数。我还需要传递参数,就像我对 applicationContext.getBean("runtimeBean", arg1, arg2) 所做的那样。看起来它在某个时候被https://jira.spring.io/browse/SPR-7431修复了

更新 5

Google Guice 有一个名为 AssistedInject 的简洁功能。 https://github.com/google/guice/wiki/AssistedInject

【问题讨论】:

  • 如果您使用 new 运算符和构造函数实例化对象,则它不是 Spring Bean,因此不符合 DI 条件。
  • 您能详细解释一下您想做什么吗?
  • @KevinBowersox 如果对象通过正确拦截的@Bean 方法返回,则不正确,例如在配置类上。不过,这听起来很像 XY 问题,而像 Spring Cloud Connectors 这样的东西可能是更好的选择。
  • @chrylis 同意,Java 配置需要 new 运算符。我更多地指的是Container 类及其对new 的使用。这不会与 Spring 一起飞行。
  • 你们说得对,我的问题是如何重新设计代码以使其工作。我想做什么?我想以某种方式重新设计代码以在配置中定义运行时 bean(但是如果我什至不知道 bean 的编号和属性怎么办),或者拥有某种可以在运行时创建 bean 并执行完整 spring 的工厂编织...其实我不知道,我需要有人解释如何正确地做事。

标签: java spring dependency-injection refactoring guice


【解决方案1】:

看来我找到了解决方案。由于我使用的是基于 java 的配置,它比您想象的还要简单。 xml 中的替代方法是查找方法,但仅从 spring 版本 4.1.X 开始,因为它支持将参数传递给方法。

这是一个完整的工作示例:

public class Container {
    private List<RuntimeBean> runtimeBeans = new ArrayList<RuntimeBean>();
    private RuntimeBeanFactory runtimeBeanFactory;

    public void load() {
        // repeated several times depending on external data/environment
        runtimeBeans.add(createRuntimeBean("Some external info1"));
        runtimeBeans.add(createRuntimeBean("Some external info2"));
    }

    public RuntimeBean createRuntimeBean(String info) {
         // should create bean which internally can have some 
         // spring annotations or in other words
         // should be managed by spring
         return runtimeBeanFactory.createRuntimeBean(info);
    }

    public void setRuntimeBeanFactory(RuntimeBeanFactory runtimeBeanFactory) {
        this.runtimeBeanFactory = runtimeBeanFactory;
    }
}

public interface RuntimeBeanFactory {
    RuntimeBean createRuntimeBean(String info);
}

//and finally
@Configuration
public class ApplicationConfiguration {
    
    @Bean
    Container container() {
        Container container = new Container(beanToInject());
        container.setBeanRuntimeFactory(runtimeBeanFactory());
        return container;
    }
        
    // LOOK HOW IT IS SIMPLE IN THE JAVA CONFIGURATION
    @Bean 
    public BeanRuntimeFactory runtimeBeanFactory() {
        return new BeanRuntimeFactory() {
            public RuntimeBean createRuntimeBean(String beanName) {
                return runtimeBean(beanName);
            }
        };
    }
    
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    RuntimeBean runtimeBean(String beanName) {
        return new RuntimeBean(beanName);
    }
}

class RuntimeBean {
    @Autowired
    Container container;
}

就是这样。

谢谢大家。

【讨论】:

  • 是的,尽管您的方法仅在 4.1.4.RELEASE 之后才有效,但您必须在上下文中简单地使用 getBean(name, ...args) 或覆盖 ConfigurationClassEnhancer 上的拦截器以便将 args 传递给构造函数
  • 基于 Java 的方法甚至可以在早期版本上工作,我错过了什么吗?
  • sss之前不接受构造函数的参数,从4.1.4开始修复
  • 在它不接受构造函数参数之前,从 4.1.4 开始已经修复。你必须记住,通过调用 return runtimeBean(beanName);您不是直接调用您的方法 runtimeBean 而是调用负责在 Spring 上下文中创建此 bean 的 bean 工厂的实例化方法,并且参数在传递给实际 bean 之前由工厂解析。如果是“@Bean”和 '@Configuration' 注释整个过程被 ConfigurationClassEnhancer.BeanFactoryAwareMethodInterceptor 拦截,它决定如何实例化你的 bean。
【解决方案2】:

我认为你的概念是错误的使用
RuntimeBean beanRuntime = createRuntimeBean();
您正在绕过 Spring 容器并使用常规 java 构造函数,因此工厂方法上的任何注释都将被忽略,并且此 bean 永远不会由 Spring 管理

这是在一种方法中创建多个原型 bean 的解决方案,看起来并不漂亮但应该可以工作,我在 RuntimeBean 中自动装配容器作为日志中显示的自动装配证明,您还可以在日志中看到每个 bean 都是原型的新实例你运行这个。

'

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);

        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        Container container = (Container) context.getBean("container");
        container.load();
    }
}

@Component
class Container {
    private List<RuntimeBean> runtimeBeans = new ArrayList<RuntimeBean>();
    @Autowired
    ApplicationContext context;

    @Autowired
    private ObjectFactory<RuntimeBean> myBeanFactory;

    public void load() {

        // repeated several times depending on external data/environment
        for (int i = 0; i < 10; i++) {
            // **************************************
            // COMENTED OUT THE WRONG STUFFF 
            // RuntimeBean beanRuntime = context.getBean(RuntimeBean.class);
            // createRuntimeBean();
            // 
            // **************************************

            RuntimeBean beanRuntime = myBeanFactory.getObject();
            runtimeBeans.add(beanRuntime);
            System.out.println(beanRuntime + "  " + beanRuntime.container);
        }
    }

    @Bean
    @Scope(BeanDefinition.SCOPE_PROTOTYPE)
    public RuntimeBean createRuntimeBean() {
        return new RuntimeBean();
    }
}

// @Component

class RuntimeBean {
    @Autowired
    Container container;

} '

【讨论】:

  • 这完美地解释了如何让它以“让它工作”的方式工作,这就是我试图用 RuntimeBeanFactory 实现的目标。但是我觉得应该有更好的解决方案。谢谢。
  • 这里的另一个问题是我的原型范围 bean 使用一些参数进行了参数化。 ObjectFactory#getObject() 不允许传递任何参数。
  • 此方法有效,与基于BeanFactoryPostProcessor 的解决方案不同。谢谢!!
【解决方案3】:

您不需要Container,因为所有运行时对象都应该由ApplicationContext 创建、持有和管理。想想一个 Web 应用程序,它们几乎是一样的。如上所述,每个请求都包含外部数据/环境信息。您需要的是一个原型/请求范围的 bean,例如 ExternalDataEnvironmentInfo,它可以通过 静态 方式读取和保存运行时数据,比如说静态工厂方法。

<bean id="externalData" class="ExternalData"
    factory-method="read" scope="prototype"></bean>

<bean id="environmentInfo" class="EnvironmentInfo"
    factory-method="read" scope="prototype/singleton"></bean>

<bean class="RuntimeBean" scope="prototype">
    <property name="externalData" ref="externalData">
    <property name="environmentInfo" ref="environmentInfo">
</bean> 

如果你确实需要一个容器来保存运行时对象,代码应该是

class Container {

    List list;
    ApplicationContext context;//injected by spring if Container is not a prototype bean

    public void load() {// no loop inside, each time call load() will load a runtime object
        RuntimeBean bean = context.getBean(RuntimeBean.class); // see official doc
        list.add(bean);// do whatever
    }
}

官方文档Singleton beans with prototype-bean dependencies.

【讨论】:

  • 感谢您的评论,我认为与我的工厂没有太大区别。它仍然是一个运行时 bean,其原型范围由容器在加载/重新加载/等时创建。我确实需要一个容器,因为它是我尝试使用 spring 重构的框架的核心类。
【解决方案4】:

一个简单的方法:

@Component
public class RuntimeBeanBuilder {

    @Autowired
    private ApplicationContext applicationContext;

    public MyObject load(String beanName, MyObject myObject) {
        ConfigurableApplicationContext configContext = (ConfigurableApplicationContext) applicationContext;
        SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();

        if (beanRegistry.containsSingleton(beanName)) {
            return beanRegistry.getSingleton(beanName);
        } else {
            beanRegistry.registerSingleton(beanName, myObject);

            return beanRegistry.getSingleton(beanName);
        }
    }
}


@Service
public MyService{

   //inject your builder and create or load beans
   @Autowired
   private RuntimeBeanBuilder builder;

   //do something
}

你可以使用这个来代替 SingletonBeanRegistry:

BeanFactory beanFactory = configContext.getBeanFactory();

无论如何,SingletonBeanBuilder 扩展了 HierarchicalBeanFactory 并且 HierarchicalBeanFactory 扩展了 BeanFactory

【讨论】:

    【解决方案5】:

    可以使用BeanFactoryPostProcesor 动态注册bean。在这里,您可以在应用程序启动时执行此操作(spring 的应用程序上下文已被初始化)。您不能最新注册 bean,但另一方面,您可以为您的 bean 使用依赖注入,因为它们成为“真正的”Spring bean。

    public class DynamicBeansRegistar implements BeanFactoryPostProcessor {
    
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            if (! (beanFactory instanceof BeanDefinitionRegistry))  {
                throw new RuntimeException("BeanFactory is not instance of BeanDefinitionRegistry");
            }   
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    
            // here you can fire your logic to get definition for your beans at runtime and 
            // then register all beans you need (possibly inside a loop)
    
            BeanDefinition dynamicBean = BeanDefinitionBuilder.    
                 .rootBeanDefinition(TheClassOfYourDynamicBean.class) // here you define the class
                 .setScope(BeanDefinition.SCOPE_SINGLETON)
                 .addDependsOn("someOtherBean") // make sure all other needed beans are initialized
    
                 // you can set factory method, constructor args using other methods of this builder
                
                 .getBeanDefinition();
    
            registry.registerBeanDefinition("your.bean.name", dynamicBean);           
    
    }
    
    @Component
    class SomeOtherClass {
    
        // NOTE: it is possible to autowire the bean
        @Autowired
        private TheClassOfYourDynamicBean myDynamicBean;
    
    }
    

    如上所述,您仍然可以使用 Spring 的依赖注入,因为后处理器在实际的应用程序上下文上工作。

    【讨论】:

      猜你喜欢
      • 2012-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2013-09-06
      • 2015-06-15
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      相关资源
      最近更新 更多