在一个普通类中使用bean,代码如下:
public class ReceiveThread extends Thread { @Autowired private ApplicationContext ctx; ConcentratorService concentratorService; public void init() { ctx = new FileSystemXmlApplicationContext("/WebRoot/WEB-INF/config/datasource.xml"); concentratorService =(ConcentratorService) ctx.getBean("concentratorService"); } public void run() { String macAddr="12:12:12:12:12:12"; Concentrator c=concentratorService.findConcentratorByCaddress(macAddr); } }
运行多线程之后,service被成功注入了,但是dao为空的。
ConcentratorService中的findConcentratorByCaddress函数如下:
@Service("ConcentratorService") public class ConcentratorServiceImpl implements ConcentratorService{ @Autowired ConcentratorDao concentratorDao; public Concentrator findConcentratorByCaddress(String caddress) throws Exception{ // TODO Auto-generated method stub return concentratorDao.findConcentratorByCaddress(caddress); } }
各位,求救!
============更新内容============
ConcentratorDao:(ConcentratorService雷同,只是把Dao改成Service)
public interface ConcentratorDao { public ListgetConcentratorListByMacAddresses(String[] macAddr) throws Exception; }
datasource.xml片段
两种方式
1.每次调用这个你所谓的普通类的方法时,在外部依赖dao,把dao实例传进来,并且删掉这个普通类里的关于spring的代码.
2.把你这个普通类加注解@Component,使当前类被spring管理,给scope为多例,并在类里依赖注入你的dao及service.
update:
先在spring中加上这个bean:
然后在你要使用线程的类里面注入
用直接就是executor.execute();