在Service中注入Dao不成功,Dao为null。 财富值93

2016-10-12 08:05发布

在一个普通类中使用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);     } }

各位,求救!

付费偷看设置
发送
7条回答
bbjbbj - 这个人很懒,什么都没留下
1楼 · 2016-10-12 08:36.采纳回答

两种方式
1.每次调用这个你所谓的普通类的方法时,在外部依赖dao,把dao实例传进来,并且删掉这个普通类里的关于spring的代码.
2.把你这个普通类加注解@Component,使当前类被spring管理,给scope为多例,并在类里依赖注入你的daoservice.

这个又是啥意思?

另外你的ConcentratorServiceImpl真的有被IoC容器管理吗?如果被IoC容器管理而未找到concentratorDao,又没有在@Autowired上设置required=false。这种情况concentratorDao不可能会为null的吧,spring找不到对应的bean依赖,应该会直接出现Dependency Exception才正确。

注入ApplicationContext

你这个逻辑写的让人真的看不懂啊。

我认为大概这种情况下可能会出现 dao 为空

要不然可能就是自己的代码改了 dao 值

一周热门 更多>