编写一个获取上下文全部的bean的工具类app
public class SpringContextUtil implements ApplicationContextAware{ // Spring应用上下文环境 private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口的回调方法,设置上下文环境 */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 获取对象 这里重写了bean方法,起主要做用 * example: getBean("userService")//注意: 类名首字母必定要小写! */ public static Object getBean(String beanId) throws BeansException { return applicationContext.getBean(beanId); } }
线程类里面调用ide
public class ProductThread implements Runnable{
private final ProductService productService = (ProductService) SpringContextUtil.getBean("productService");
private final IntegralOrderService integralOrderService = (IntegralOrderService) SpringContextUtil.getBean("integralOrderService");
private Integer type;
private Integer productId;
private Integer userId;
public ProductThread(Integer type,Integer productId,Integer userId){
this.type = type;
this.productId = productId;
this.userId = userId;
}
@Override
public void run() {
//添加
System.out.println("进入线程!");
if(type==1){
this.placeAnOrder(productId,userId);
}
}
public void placeAnOrder(Integer productId,Integer userId){
*******************
}
}
这样就能够了,可是有一点,若是线程写成内部类,就不用写工具类。工具