SpringBoot動的Beanの作成

2190 ワード

SpringBootテストバージョン:1.3.4.RELEASE
参照コードは次のとおりです.
package com.spring.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
/**
 *  conditional , true , bean
 */
@ConditionalOnExpression("${my.configuration.enabled}")
public class DynamicConfiguration
{
	@Autowired
	private ApplicationContext applicationContext;
	
	/**
	 *  Runnable , 
	 */
	@Bean
	public Runnable dynamicConfiguration() throws Exception
	{
		ConfigurableApplicationContext context = (ConfigurableApplicationContext)applicationContext;
		DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)context.getBeanFactory();
		
		BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(UserService.class);
		/**
		 *  
		 */
		beanDefinitionBuilder.addPropertyValue("name", "myConfigure");
		beanDefinitionBuilder.addPropertyValue("jdbcTemplate", applicationContext.getBean(JdbcTemplate.class));
		
		/**
		 *  spring 
		 */
		beanFactory.registerBeanDefinition("userService", beanDefinitionBuilder.getBeanDefinition());
		return null;
	}
}
class UserService
{
	private String name;
	private JdbcTemplate jdbcTemplate;
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public JdbcTemplate getJdbcTemplate()
	{
		return jdbcTemplate;
	}
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate)
	{
		this.jdbcTemplate = jdbcTemplate;
	}
}

その後、次のようにオブジェクトを取得できます.
applicationContext.getBean(UserService.class);
applicationContext.getBean("userService", UserService.class)