Java Spring依赖注入不起作用

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

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:

@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:

Java Spring依赖注入不起作用

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.

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:

确定