spring 框架通过new Object()获取applicationContext 中的bean方案
工作中,需要手动创建一个对象,但用到了spring容器中对象的业务逻辑,这时候就要去通过获取容器中的对象。这时候,可以通过实例化一个实现了ApplicationContextAware接口的类获取spring容器对象,从而获取容器中的bean。
直接上代码,如下:
package com.blue.forum.context; import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.core.ResolvableType; /** * @ClassName: ServletContextHolder * @author * @date 2015年12月9日 下午6:23:17 */ public class AppContext implements ApplicationContextAware { protected static ApplicationContext context; public AppContext() { super(); System.out.println("------------初始化"); // TODO Auto-generated constructor stub } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { System.out.println("初始化http.xml的 context================:"+context.toString()+"class:"+context.getApplicationName()); if (null == AppContext.context) AppContext.context = context; } public static ApplicationContext getContext() { return AppContext.context; } public static final Object getBean(String name) throws BeansException { return AppContext.context.getBean(name); } public static final <T> T getBean(String name, Class<T> requiredType) throws BeansException { return AppContext.context.getBean(name, requiredType); } public static final <T> T getBean(Class<T> requiredType) throws BeansException { return AppContext.context.getBean(requiredType); } public static final Object getBean(String name, Object... args) throws BeansException { return AppContext.context.getBean(name, args); } public static final <T> T getBean(Class<T> requiredType, Object... args) throws BeansException { return AppContext.context.getBean(requiredType, args); } public static final boolean containsBean(String name) { return AppContext.context.containsBean(name); } public static final boolean isSingleton(String name) throws NoSuchBeanDefinitionException { return AppContext.context.isSingleton(name); } public static final boolean isPrototype(String name) throws NoSuchBeanDefinitionException { return AppContext.context.isPrototype(name); } public static final Class<?> getType(String name) throws NoSuchBeanDefinitionException { return AppContext.context.getType(name); } public static final String[] getAliases(String name) { return AppContext.context.getAliases(name); } }
值得注意的是,当项目启动的时候必须对此类进行实例化,否则使用时可能会出现空指针异常,即拿不到容器对象。
稳妥的配置如下:
<bean class="com.blue.forum.context.AppContext" lazy-init="false"></bean>
这样,妈妈再也不用担心由于懒加载出现的拿不到对象的问题了。
业务驱动技术,技术是手段,业务是目的。