編寫一個獲取上下文全部的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){
*******************
}
}
這樣就能夠了,可是有一點,若是線程寫成內部類,就不用寫工具類。工具