首页 > 解决方案 > 无法使用 configurationproperties 注释读取属性

问题描述

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Application.class, args);
        GlobalProperties globalProperties = context.getBean(GlobalProperties.class);
        System.out.println(globalProperties);
    }
}

@Component
@PropertySource("classpath:global.yml")
@ConfigurationProperties("app")
public class GlobalProperties {

    private String error;
    private List<Menu> menus = new ArrayList<>();
    private Compiler compiler = new Compiler();

    public static class Menu {
        private String name;
        private String path;
        private String title;

    //getters and setters and tostring

    }

    public static class Compiler {
        private String timeout;
        private String outputFolder;

    //getters and setters and tostring
    }


    @Override
    public String toString() {
        return "GlobalProperties [error=" + error + ", menus=" + menus + ", compiler=" + compiler + "]";
    }


}

src/main/resources 文件夹中的 global.yml 文件

logging:
  level:
    org.springframework.web: ERROR
    com.mkyong: DEBUG
email: test@mkyong.com
thread-pool: 10
app:
  menus:
    - title: Home
      name: Home
      path: /
    - title: Login
      name: Login
      path: /login
  compiler:
    timeout: 5
    output-folder: /temp/
  error: /error/

当我运行应用程序时,我没有看到 global.yml 属性被正确读取。我把它当作 o/p

GlobalProperties [error=null, menus=[], compiler=Compiler{timeout='null', outputFolder='null'}]

我是否错过了上述代码中的任何内容以从 yml 文件中读取属性。我也尝试用 global.properties 替换 global.yml ,但这也没有用。

标签: javaspringspring-boot

解决方案


您必须将设置器添加到您的 GlobalProperties 类,就像您为嵌套静态类所做的那样。


推荐阅读