由於spring在java開發中的廣泛運用大大的方便了開發的同時,當運用一些技術比如多線程等
在由spring管理的配置文件中,可以通過封裝spring提供工具,手動獲得spring管理的bean,這樣
既可以方便使用bean,又可以同時使用其他技術。
可以方便的使用多種技術,而不至於由於使用spring導致不好用。
package com.jd.app.server.irp.service.task;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Created by liubaofeng on 2017/1/20.
*/
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanUtil.applicationContext = applicationContext;
}
public static Object getBeanByName(String beanName) {
if (applicationContext == null){
return null;
}
return applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> type) {
return applicationContext.getBean(type);
}
}
spring xml中配置<bean id="springBeanUtil" class="com.jd.app.server.irp.service.task.SpringBeanUtil"/>
xml中配置很關鍵,因需要spring加載時感知,不配置取不到spring管理的bean。
相關連接
http://www.cnphp6.com/archives/135859