场景:
在代码中需要动态获取其它bean
实例代码:
01 | package org.company.xxx; |
03 | import org.springframework.beans.BeansException; |
04 | import org.springframework.context.ApplicationContext; |
05 | import org.springframework.context.ApplicationContextAware; |
08 | * 获取spring容器,以访问容器中定义的其他bean |
10 | public class SpringContextUtil implements ApplicationContextAware { |
13 | private static ApplicationContext applicationContext; |
16 | * 实现ApplicationContextAware接口的回调方法,设置上下文环境 |
18 | public void setApplicationContext(ApplicationContext applicationContext) |
19 | throws BeansException { |
20 | SpringContextUtil.applicationContext = applicationContext; |
23 | public static ApplicationContext getApplicationContext() { |
24 | return applicationContext; |
28 | * 获取对象 这里重写了bean方法,起主要作用 |
31 | * <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a> Object 一个以所给名字注册的bean的实例 |
32 | * @throws BeansException |
34 | public static Object getBean(String beanId) throws BeansException { |
35 | return applicationContext.getBean(beanId); |
Bean配置:
1 | < beanid = "SpringContextUtil" class = "org.company.xxx.SpringContextUtil" /> |
注:
1、实现了ApplicationContextAware接口,在Bean的实例化时会自动调用setApplicationContext()方法!
web服务器启动时, 会首先建立WebApplicationContext,这是整个spring的上下文,你可以理解为spring的框架实例。 然后会初始化你在xml文件或通过注解定义的bean,当spring发现实例化的bean实现了ApplicationContextAware 接口时,就会在初始化完成后调用setApplicationContext方法,将spring 的上下文实例传入。
2、通过调用静态方法getBean即可获取
3.spring的getbean和new出来的对象有什么区别
个人觉得,主要是解耦
比如你有一个A类 在好几个类里边要调用到A的方法 new的话就要在每个类里都new A()
spring的话 只要配置一个bean进行注入就够了。
哪天你不用A类了 改成B了~ 直接把bean里边的class改成B就搞定了
如果用new的话 要改好几个地方~