一个 Spring 的问题

2017-05-15 18:37:43 +08:00
 mikicomo

如图,我用注解自动装配不了,报空指针异常,debug 值为 NULL 现在我只能用构造函数来手动装配曲线救国,这是什么问题导致的自动装配失败的?

可能是哪里出的问题?

1742 次点击
所在节点    问与答
8 条回复
LaudOak
2017-05-15 18:42:12 +08:00
姿势不对吧,Bean 那边怎么定义的
mikicomo
2017-05-15 18:44:51 +08:00
@LaudOak
```
@Service("ItemIndexService")
public class ItemIndexServiceImpl implements ItemIndexService {

@Autowired
private ItemIndexMapper itemindexmapper;


@Transactional
public ItemIndex selectById(int id) {
return itemindexmapper.selectById(id);

}

@Transactional
public List<ItemIndex> findAll() {

List<ItemIndex> findAll = itemindexmapper.findAll();
return findAll;
}

@Transactional
public int deleteItemIndex(int id) {
return itemindexmapper.deleteItemIndex(id);

}

@Transactional
public int insertItemIndex(ItemIndex itemindex) {

return itemindexmapper.insertItemIndex(itemindex);
}

@Transactional
public int updateItemIndex(ItemIndex itemindex) {

return itemindexmapper.updateItemIndex(itemindex);
}

}
```
acrisliu
2017-05-15 18:53:34 +08:00
你这个类是 spring 组件么?加了 @Component 注解没
mikicomo
2017-05-15 18:58:26 +08:00
@acrisliu
```
public class ExcelDataPackage {

@Autowired
@Qualifier("ItemIndexService")
private ItemIndexService itemIndexService;

@Autowired
@Qualifier("ItemDetailService")
private ItemDetailService itemDetailService;

private List<ItemIndex> itemIndices;

public int findIndexCache(ItemIndex index){
}

public void bindObject(){

}

public void insertObject(){

}


}

```

我没有加 @Component 注解,我这里只要装配就好了,本身不需要作为一个组件来使用,不用加 @Component 的吧?
而且我加了也依旧装不上
stackboom
2017-05-15 19:06:53 +08:00
这个类 你 new 出来的吧 。
mikicomo
2017-05-15 19:12:47 +08:00
@stackboom
卧槽...是的....我为了方便在 test 里面直接 psvm 里面 new 了,应该是要在 @Controller 或者别的 Compant 下面让 Spring 再把我这个类本身也装配进来是吧》。。。。
stackboom
2017-05-15 19:16:05 +08:00
@mikicomo #6 test 使用 spring test+ junit 也可以注入, 如果你是 psvm 从 spring 容器取吧。这样 spring
才会帮你注入。
mikicomo
2017-05-15 19:21:31 +08:00
@stackboom 嗯,还是在思维方式上还没有交给容器来管理这样的思维习惯。。。搞了好几个小时这个问题,谢谢大兄弟了!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/361503

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX