Java Spring依赖注入不起作用

huangapple go评论86阅读模式
英文:

Java Spring dependency injection not working

问题

I am very new to Java Spring and I tried to set up 2 classes and a Test for one of them. That is my project structure:

Java Spring依赖注入不起作用

Here is the code for the classes:

  1. @Component
  2. public class Box {
  3. private Item item;
  4. @Autowired
  5. public Box(Item item) {
  6. this.item = item;
  7. }
  8. public Item getItem() {
  9. return item;
  10. }
  11. }
  1. @Configuration
  2. @ComponentScan
  3. public class BoxConfig {}
  1. @Component
  2. public class Item {}

And here is the code of the JUnit Test I wrote in the BoxTest class:

  1. @ContextConfiguration(classes = {BoxConfig.class})
  2. public class BoxTest {
  3. @Autowired
  4. Box box;
  5. @Test
  6. public void BoxTest1() {
  7. Assertions.assertNotNull(box.getItem());
  8. }
  9. }

My Expectation was, that Spring automatically injects a box object into the box attribute of the Test, but the box attribute ist always null so I keep getting a NullReferenceException. Does someone know why it is not properly initialised?

英文:

I am very new to Java Spring and I tried to set up 2 classes and a Test for one of them. That is my project structure:

Java Spring依赖注入不起作用

Here is the code for the classes:

<!-- language: java -->

  1. @Component
  2. public class Box {
  3. private Item item;
  4. @Autowired
  5. public Box(Item item) {
  6. this.item = item;
  7. }
  8. public Item getItem() {
  9. return item;
  10. }
  11. }

<!-- language: java -->

  1. @Configuration
  2. @ComponentScan
  3. public class BoxConfig {}

<!-- language: java -->

  1. @Component
  2. public class Item {}

And here is the code of the JUnit Test I wrote in the BoxTest class:
<!-- language: java -->

  1. @ContextConfiguration(classes = {BoxConfig.class})
  2. public class BoxTest {
  3. @Autowired
  4. Box box;
  5. @Test
  6. public void BoxTest1() {
  7. Assertions.assertNotNull(box.getItem());
  8. }
  9. }

My Expectation was, that Spring automatically injects a box object into the box attribute of the Test, but the box attribute ist always null so I keep getting a NullReferenceException. Does someone know why it is not properly initialised?

答案1

得分: 1

BoxTest 需要以某种方式包含在 Spring 配置中。
例如,使用 @ExtendWith(SpringExtension.class) 会有帮助。

您可以在Spring文档中查看其他选项。

英文:

BoxTest needs to be included in Spring configuration somehow.
E.g. using @ExtendWith(SpringExtension.class) would help.

You can look at other options in Spring documentation.

huangapple
  • 本文由 发表于 2023年3月7日 21:59:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定