springboot-中工具类,普通方法,和quartz的Job中获取bean的方法
ApplicationContextAware
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
/**
* 主要讲applicationcontext对象注入进该类,从而我们可以在普通项目中获取bean
*/
public final class BeanDefinedLocator implements ApplicationContextAware {
private static final BeanDefinedLocator beanLocator = new BeanDefinedLocator();
private ApplicationContext context = null;
private BeanDefinedLocator() {}
public static BeanDefinedLocator getInstance() {
return beanLocator;
}
public ApplicationContext getApplicationContext(){
return context;
}
public void setApplicationContext(ApplicationContext applicationcontext) throws BeansException {
beanLocator.context = applicationcontext;
}
public Object getBean(String beanName) {
Assert.hasText( beanName );
return this.context.getBean(beanName);
}
/**
* 根据指定的bean名及类型来获取bean
* @param <T>
* @param beanName
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public <T> T getBean(String beanName, Class<T> clazz) {
Assert.hasText( beanName );
contextNotNull();
return (T) this.context.getBean(beanName, clazz);
}
/**
* 根据指定的类型来获取bean
* @param <T>
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public <T> T getBean(Class<T> clazz) {
Assert.notNull( clazz );
contextNotNull();
return (T) BeanFactoryUtils.beansOfTypeIncludingAncestors(this.context, clazz, true, true).values().iterator().next();
}
/**
* 根据指定的类型来获取bean集合
* @param <T>
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public <T> List<T> getBeans(Class<T> clazz) {
Assert.notNull( clazz );
contextNotNull();
return new ArrayList<T>(BeanFactoryUtils.beansOfTypeIncludingAncestors(this.context, clazz, true, true).values());
}
private void contextNotNull() {
if (this.context == null)
throw new ApplicationContextException("application context is null");
}
SpringBeanAutowiringSupport(项目必须是web项目)
public class InitServlet extends HttpServlet {
@Autowired
private ServiceA serviceA;
public void init(ServletConfig config) throws ServletException {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
assertNotNull("Service should be injected.", serviceA);
}
// Omitted doGet(req, res), doPost(req, res);
}
public class DumpJob implements Job {
@Autowired
private ServiceA serviceA;
public void execute(JobExecutionContext context) throws JobExecutionException {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
assertNotNull("Service should be injected.", serviceA);
}
}