1 . 通过spring提供的ContextLoader获取
ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
personSecurityService = (PersonSecurityService) context.getBean("personSecurityService");
2. 在线程中获取bean
通过继承ApplicationContextAware.java类来获取。注意:该类也需要在spring中注册
@Service
public class SpringApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
SpringApplicationContextHolder.context = context;
}
public static Object getSpringBean(String beanName) {
return context == null ? null : context.getBean(beanName);
}
public static String[] getBeanDefinitionNames() {
return context.getBeanDefinitionNames();
}
}
参考: http://www.dexcoder.com/selfly/article/326