示例
/**
* 手動獲取Spring上下文和Bean對象
*
* @Author YinWenBing
* @Date 2017/1/6 17:07
*/
public class ApplicationUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 加載Spring配置文件時,如果Spring配置文件中所定義的Bean類實現了ApplicationContextAware接口,會自動調用該方法
*
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationUtil.applicationContext = applicationContext;
}
/**
* 獲取Spring上下文
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 獲取Spring Bean
* @param name
* @return
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
在Spring配置文件中手動配置ApplicationUtil Bean
<bean id="applicationUtil" class="com.nb.soa.common.util.ApplicationUtil"></bean>