英文:
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:
Here is the code for the classes:
@Component
public class Box {
private Item item;
@Autowired
public Box(Item item) {
this.item = item;
}
public Item getItem() {
return item;
}
}
@Configuration
@ComponentScan
public class BoxConfig {}
@Component
public class Item {}
And here is the code of the JUnit Test I wrote in the BoxTest class:
@ContextConfiguration(classes = {BoxConfig.class})
public class BoxTest {
@Autowired
Box box;
@Test
public void BoxTest1() {
Assertions.assertNotNull(box.getItem());
}
}
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:
Here is the code for the classes:
<!-- language: java -->
@Component
public class Box {
private Item item;
@Autowired
public Box(Item item) {
this.item = item;
}
public Item getItem() {
return item;
}
}
<!-- language: java -->
@Configuration
@ComponentScan
public class BoxConfig {}
<!-- language: java -->
@Component
public class Item {}
And here is the code of the JUnit Test I wrote in the BoxTest class:
<!-- language: java -->
@ContextConfiguration(classes = {BoxConfig.class})
public class BoxTest {
@Autowired
Box box;
@Test
public void BoxTest1() {
Assertions.assertNotNull(box.getItem());
}
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论