【问题标题】:unable to read properties using configurationproperties annotation无法使用 configurationproperties 注释读取属性
【发布时间】:2018-07-22 22:03:05
【问题描述】:
@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,但也没有用。

【问题讨论】:

  • 在 GlobalProperties 中使用 @Configuration 而不是 Component 注释...如果有帮助请告诉我

标签: java spring spring-boot


【解决方案1】:

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

【讨论】:

  • 添加了 getter 和 setter,我要做的另一件事是将 global.yml 文件中的所有内容移动到 application.yml 以使其工作。 @propertysource 不工作,尝试使用 yml 和 .properties 文件的 propertysource。 propertysource 不起作用的任何原因?
  • propertysource 适用于 .properties 文件,但我还需要有组件注释。没有组件注释,propertysource 不能与 enableconfigurationsource 注释一起使用
【解决方案2】:

作为一般规则,带有局部变量的 spring @component 类需要为这些变量设置 setter(并且 getter 也是一个好习惯)。 spring 使用无参数构造函数来制造 bean 和组件,并利用 setter 来初始化变量。 这当然也适用于@component 3 个子类型:@service@repository@controller

如果您要添加任何其他构造函数(这将覆盖默认存在的“不可见”无参数构造函数),请确保显式编写无参数构造函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-05
    • 2015-11-04
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    相关资源
    最近更新 更多