转自:http://blog.sina.com.cn/s/blog_9c7ba64d0101evar.html Java类获取spring 容器的bean 方法一:在初始化时保存ApplicationContext对象 代码: 1 ApplicationContext ac = new FileSystemXmlApplicationContext('applicationContext.xml');
2 ac.getBean('beanId');
说明:这种方式适用于采用Spring框架的独立应用程序,需要程序通过配置文件手工初始化Spring的情况。 1 import org.springframework.web.context.support.WebApplicationContextUtils; 2 ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); 3 ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); 4 ac1.getBean('beanId'); 5 ac2.getBean('beanId'); 说明:这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。 1 package quartz.util;
2
3 import org.springframework.beans.BeansException;
4 import org.springframework.context.ApplicationContext;
5 import org.springframework.context.ApplicationContextAware;
6
7 public class SpringConfigTool implements ApplicationContextAware{//extends ApplicationObjectSupport{
8
9 private static ApplicationContext context = null;
10 private static SpringConfigTool stools = null;
11 public synchronized static SpringConfigTool init(){
12 if(stools == null){
13 stools = new SpringConfigTool();
14 }
15 return stools;
16 }
17
18 public void setApplicationContext(ApplicationContext applicationContext)
19 throws BeansException {
20 context = applicationContext;
21 }
22
23 public synchronized static Object getBean(String beanName) {
24 return context.getBean(beanName);
25 }
26
27 }
XML文件中的配置信息 |
|
来自: liang1234_ > 《springboot》