SpringBoot配置报错之java.lang.IllegalStateException
package com.sjl.domain;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;import java.util.Arrays;
import java.util.List;
import java.util.Map;/**
- 建一个 Person 类模型,里面封装 6 个属性及其 get、set、toString 方法
- */
@Component//将该组件注入到 Spring 容器中
@ConfigurationProperties(prefix = "person")
//相当于是将配置文件中所有以 person 开头的值注入到当前类中。 注意:在 pom 里要添加 processor 包
public class Person {
//...
}
package com.test;import com.springboot.app.SpringbootexerciseApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.sjl.domain.Person;
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(classes = SpringbootexerciseApplication.class)
public class test {
@Autowired
private Person person;@Test </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> contextLoads() { System.out.println(</span>"person="+<span style="color: rgba(0, 0, 0, 1)">person); }
}
package com.springboot.app;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication(scanBasePackages = "com.sjl.*")
public class SpringbootexerciseApplication {</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> main(String[] args) { SpringApplication.run(SpringbootexerciseApplication.</span><span style="color: rgba(0, 0, 255, 1)">class</span><span style="color: rgba(0, 0, 0, 1)">, args); }
}
运行 contextLoads 报错,错误现象如下:
看到这个报错后,按照提示进行修改,在网上看了一下有几种解决方案。
在测试类添加如下配置,即加上@SpringBootTest(classes=SpringbootexcrciseApplication.class)这个等价于 Spring 里面的上下文环境 ApplicationContext,并在这里面加载整个工程文件
但是加载后,显示注入值的依赖出现了问题,于是将 @Autowired private Person person; 中 @Autowired 于是把改为 @Autowired(required=false),不强制注入值,结果可以了,但是注入的值为 null,于是有百思不得其解,因为已经加了 @Component 注解了为什么还没有注入到容器中去,分析了 @SpringBootApplication 源码后,
发现该注解只是扫描当前包路径,所以,现在有两种做法:
方法一:将测试类移到注入类这个包下。
方法二:配置启动类的扫描路径。(如SpringbootexerciseApplication 类的加粗部分)
说明:先看错误日志,错误日志为首要参考标准,网上去查是第二步,因为网上的说法太多了,情况也不一样。
-------------------------------------------------------------------------------------------------------------------------------
分析 @SpringBootApplication 这个注解,一般是放到启动类上面,作用有如下三个:
1)@SpringBootConfiguration 标明该类为配置类。
2) @EnableAutoConfiguration 启动自动配置功能。
3)@ComponentScan 包扫描器,默认扫描启动类的当前包路径,可以设置 (scanBasePackages = "xxx.xxx.*"),指定扫描包路径时,注意包路径是否扫描正确,如 com.controller.* 和 com.controller 是有区别的,后者是扫描 controller 包下的所有,而前者是在后者基础上再加了一个路径相当于多了一个 "/",所以,当有扫描配置,且把一个类进行了标注,但是仍然没有被注入到 Spring 容器中,就要检查路径是否有问题。