zoukankan      html  css  js  c++  java
  • spring boot @Value 报错

    结论: 

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

      

  • 相关阅读:
    搭建聊天机器人Bot Framework
    UsernamePasswordAuthenticationToken
    在JavaWeb项目中URL中字符串加密解密方案
    python自定义库文件路径
    difference between collection and association mapping in mybatis 3
    statpot:使用mongo+bootstrap+highcharts做统计报表
    Android仿微信SlideView聊天列表滑动删除效果
    Android Studio 运行、编译卡死的解决办法
    Android wear
    android实现json数据的解析和把数据转换成json格式的字符串
  • 原文地址:https://www.cnblogs.com/swing07/p/14083120.html
Copyright © 2011-2022 走看看