使用Spring @Autowired注入一个对象,运行时为null

peter20091001 2017-06-20 03:58:31
要注入的类
@Service("companyService")
public class CompanyServiceImpl implements CompanyService {

private CompanyMapper companyMapper;

public CompanyMapper getCompanyMapper() {
return companyMapper;
}
@Autowired
public void setCompanyMapper(CompanyMapper companyMapper) {
this.companyMapper = companyMapper;
}

@Override
public int insert(Company com) {
// TODO Auto-generated method stub
return companyMapper.insert(com);
}

}
测试类(正常运行)
@RunWith(SpringJUnit4ClassRunner.class)
//告诉junit spring配置文件
@ContextConfiguration({ "classpath:spring-mybatis.xml", "classpath:spring.xml" })
public class CompanyServiceTest {
@Autowired
private CompanyService service;
@Test
public void testInsert() {
Company c = new Company();
c.setName("ppp");
c.setBoss("yu");
service.insert(c);
}
}
项目中,我在一个线程中注入
public class GetDataRunnable implements Runnable {
private CompanyService companyService;
@Autowired
public void setCompanyService(CompanyService companyService) {
this.companyService = companyService;
}

@Override
public void run() {
//业务操作
}
}
在run()方法中调用service.insert(com)
报了NullPointerException
为什么会这样?求高手指教!
...全文
13866 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
张晓花 2017-10-24
  • 打赏
  • 举报
回复
你的主要问题是spring没有扫描到对应的注解对应的service层。spring的注入有他一套注入的机制,controller 层需要注入service,service层注入dao,环环相扣,至于具体的原因需要去对应的源码跟一下就明白了。您的问题显然是注解的混乱使用,导致注入混乱。spring扫描不到对应的文件。junit 测试成功是因为spring已经默默的将该类做对应的注入配置处理。
微wx笑 2017-08-18
  • 打赏
  • 举报
回复
为什么写的那么麻烦,以下就可以了。 @Autowired private CompanyMapper companyMapper;
  • 打赏
  • 举报
回复
引用 6 楼 silyvin 的回复:
GetDataRunnable这个线程类没有被spring托管,是new出来的,肯定不能注入啊 线程中要这样获取bean ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring.xml"); ac.getBean("companyService");
顶楼上
pois 2017-06-26
  • 打赏
  • 举报
回复
GetDataRunnable这个线程类没有被spring托管,是new出来的,肯定不能注入啊 线程中要这样获取bean ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring.xml"); ac.getBean("companyService");
a_b_a_b_a_b_a_b 2017-06-26
  • 打赏
  • 举报
回复
启动线程时最好把service传入,而不是在里面注入,很容易为空。原因不知道。
z896709283 2017-06-26
  • 打赏
  • 举报
回复
引用 3 楼 csder_xj 的回复:
没有被扫描到
没有扫描到为啥测试能跑通
什么都不能 2017-06-21
  • 打赏
  • 举报
回复
@Autowire CompanyMapper companyMapper = null;
忘记呼吸 2017-06-21
  • 打赏
  • 举报
回复
没有被扫描到
xiaovhao 2017-06-20
  • 打赏
  • 举报
回复
感觉是你GetDataRunnable 这个类所在的包没有被扫描到

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧