結論:
檢查你編譯后, target 文件下的配置文件是存在,不存在會出現錯誤。
一般配置信息加載報錯,要注意檢查配置文件格式是否對,是否有引入。
我出現@Value 報錯的情況比較特殊。 我在控制器的代碼里正常使用。啟動時報錯 注入錯誤。
@RestController
@Data
public class HelloController {
@Resource
private UserServiceImpl userServiceImpl;
@Resource
private UserMongoRepository userMongoRepository;
@Value("${com.neo.title}") // 這里加載配置
private String title;
@GetMapping("/")
public Map<String,String> index(@RequestParam(name = "name", defaultValue="world") String para) {
Map<String,String> ret = new HashMap<>();
ret.put("title","hello"+para+title);
ret.put("name","我");
return ret;
}
}
通過控制台報錯信息能看出是由於控制器注入com.neo.title 時,找不到,但是我配置文件明明是寫了的。
百思不得其解,后面想想是不是配置文件運行時沒有。 后面查看果然是target目錄里 配置文件沒有。
為什么會出現這種情況呢?
主要由於是 我添加 maven 多環境配置時,添加resources 文件過濾時復制過來的代碼,配置的是yml格式文件,沒有配置properties格式文件造成。
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<!--排除配置文件-->
<resource>
<directory>src/main/resources</directory>
<!--先排除所有的配置文件-->
<excludes>
<!--使用通配符,當然可以定義多個exclude標簽進行排除-->
<exclude>application*.properties</exclude>
</excludes>
</resource>
<!--根據激活條件引入打包所需的配置和文件-->
<resource>
<directory>src/main/resources</directory>
<!--引入所需環境的配置文件-->
<filtering>true</filtering>
<includes>
<include>application.properties</include>
<include>application.yml</include>
<!--根據maven選擇環境導入配置文件-->
<include>application-${profile.active}.properties</include> // 缺少這里造成
<include>application-${profile.active}.yml</include>
</includes>
</resource>
</resources>
</build>
