结论: 

检查你编译后, 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>

  

 

posted on 2020-12-03 21:43  swing07  阅读(1187)  评论(0编辑  收藏  举报