方法一:在初始化时保存ApplicationContext对象 :
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("userService");
//比如:在application.xml中配置:
<bean id="userService" class="com.cloud.service.impl.UserServiceImpl"></bean>
说明:这样的方式适用于Spring框架的独立应用程序,须要程序通过配置文件初始化Spring。
方法二:通过Spring提供的工具类获取ApplicationContext对象
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");
说明:这样的方式适合于採用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象。然后在通过它获取须要的类实例。上面两个工具方式的差别是,前者在获取失败时抛出异常。后者返回null。
方法三:实现接口ApplicationContextAware:(推荐)
/**
* Spring ApplicationContext 工具类
*/
@SuppressWarnings("unchecked")
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
public static <T> T getBean(String beanName) {
if(applicationContext.containsBean(beanName)){
return (T) applicationContext.getBean(beanName);
}else{
return null;
}
}
public static <T> Map<String, T> getBeansOfType(Class<T> baseType){
return applicationContext.getBeansOfType(baseType);
}
}
说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,扫描到该类,就会通过该方法将ApplicationContext对象注入。然后在代码中就可以获取spring容器bean了。例如:
LoadExploreTree bean = SpringUtils.getBean("loadExploreTree");
方法四:继承自抽象类ApplicationObjectSupport
@Service
public class SpringContextHelper2 extends ApplicationObjectSupport {
//提供一个接口,获取容器中的Bean实例,根据名称获取
public Object getBean(String beanName)
{
return getApplicationContext().getBean(beanName);
}
}
继承类的方式,是调用父类的getApplicationContext()方法,获取Spring容器对象。
方法五:继承自抽象类WebApplicationObjectSupport
说明:类似上面方法。调用getWebApplicationContext()获取WebApplicationContext