关键点ApplicationContext对象
不废话直接上代码
、
这个是注入,代码任何地方都可以,只要当前类被spring容器所管理都可以
可以在任何代码里用转化过后的beanFactory来放对象
@Component
public class ServerChannelInitializer {
@Autowired
private ApplicationContext applicationContext;
public void test() throws Exception {
//将applicationContext转换为ConfigurableApplicationContext 只有转换了才能注入
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
//获取beanFactory对象
ConfigurableListableBeanFactory beanFactory = configurableApplicationContext.getBeanFactory();
//registerSingleton表示注入的是个单例对象,第一个参数传入bean的id,在获取时要用到
ConcurrentHashMap<String,Channel> channelsMap = new ConcurrentHashMap();
beanFactory.registerSingleton("channelsMap",channelsMap);
}
}
这个是取出
注意这种方式注入的对象不能用Autowired来获取,因为是代码运行中创建的,不是初始化的时候
@Component
public class ServerChannelInitializer {
@Autowired
private ApplicationContext applicationContext;
public void test() throws Exception {
//直接调用applicationContext getBean方法获取到实例,第一参数是bean的id,要对应着注入时的那个,后一个表示对象类型
ConcurrentHashMap<String,Channel> channelsMap = applicationContext.getBean("channelsMap", ConcurrentHashMap.class);
}
}
这样在代码任意地方都能获取到beanFactory 里的对象实例了(前提也是代码所在类是被spring容器所管理的)