Spring.注册Bean

目录

获取BeanFactory

保存注册

测试验证


获取BeanFactory

扩展接口BeanFactoryPostProcessor或者该接口的子接口,并注入Spring即可获取BeanFactory。

@Component
public class DefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) throws BeansException {
		// 测试注入HelloWord
		HelloWord beanClass = new HelloWord();
		beanFactory.registerSingleton("hello1", beanClass);
		
		// 缓存beanFactory引用
		ConfigurableListableBeanFactoryUtil.setContext(beanFactory);
	}

	public void postProcessBeanDefinitionRegistry(
			BeanDefinitionRegistry registry) throws BeansException {
	}
}

保存注册

注册:beanFactory.registerSingleton(beanName,singletonObject);

保存:使用静态属性缓存

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

/**
 * 用来缓存BeanFactory 以及 获取和注册bean
 */
public class BeanFactoryUtil {
	private static ConfigurableListableBeanFactory beanFactory;

	/**
	 * 报错beanFactory对象
	 * @param beanFactory1
	 */
	public static void setContext(ConfigurableListableBeanFactory beanFactory1) {
		beanFactory = beanFactory1;
	}
	
	/**
	 * 注册单例
	 * @param beanName
	 * @param singletonObject
	 */
	public static void registerSingleton(String beanName, Object singletonObject) {
		beanFactory.registerSingleton(beanName,singletonObject);
	}

	/**
	 * 根据Bean名称获取Bean对象
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName) {
		return beanFactory.getBean(beanName);
	}

	/**
	 * 根据类型获取Bean对象
	 * @param t
	 * @return
	 */
	public static <T> T getBean(Class<T> t) {
		return beanFactory.getBean(t);
	}
}

测试验证

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.example.spring4condition.register.BeanFactoryUtil;
import com.example.spring4condition.register.HelloWord;

@SpringBootTest(classes = Spring4ConditionApplication.class)
@RunWith(SpringRunner.class)
public class TestReristeBean {
	
	@Autowired(required = false)
	@Qualifier("hello1")
	private HelloWord hello1;
	
	@Test
	public void test3(){
		 System.out.println("hello1:"+this.hello1);
		
		HelloWord beanClass = new HelloWord();
		BeanFactoryUtil.registerSingleton("hello2", beanClass);
		
		HelloWord hello2 = (HelloWord) BeanFactoryUtil.getBean("hello2");
		System.out.println("hello2:" + hello2.say());
		
	}
}

end ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闲猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值