使用Spring @Autowired注入一个对象,运行时为null
要注入的类
@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
为什么会这样?求高手指教!