Autowired无法自动装配或值为null

问题

写的配置类无法在SpringBoot的ApplicationTests类中自动装配且装配为null

原因

无法自动装配为idea报错,原因为main/java下没有@SpringBootApplication的主类。

装配为null的原因是Test类注解没写对,未启动Spring容器

测试类

2.2版本之前
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package cn.edu.scnu;
import org.junit.Test;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private Xxxx xxxx;
@Test
public void contextLoads(){
System.out.println(xxxx);
}
}
2.2版本之后
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package cn.edu.scnu;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class ApplicationTests {
@Autowired
private Xxxx xxxx;
@Test
void contextLoads() {
System.out.println(xxxx);
}
}

其中低版本需要加@RunWith(SpringRunner.class)注解,且不能省略public修饰符

[CSDN]: https://blog.csdn.net/dl962454/article/details/109721180 “[SpringBoot]@Component加入容器之后@Autowired注入为null解决”