当前位置: 首页 > 知识库问答 >
问题:

ConfigurationProperties不绑定属性

南门棋
2023-03-14

我想通过使用@ConfigurationProperties注释将我的Application.Properties自动绑定到一个类中。首先,我尝试了@value注释,并能够将属性值注入类变量。但是,@ConfigurationProperties没有将属性注入到值中。

我的应用程序.属性:

spring.jpa.show-sql=false
my.url=my_url
my.name=muatik

application.java

package com.muatik;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;


@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        final ApplicationContext ctx = SpringApplication.run(Application.class, args);
        final ConfigBinder confs = ctx.getBean(ConfigBinder.class);
        System.out.println(confs.getUrl());
        System.out.println(confs.getName());
    }

}

ConfigBinder.java

package com.muatik;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;



@Component
@ConfigurationProperties(prefix="my")
public class ConfigBinder {

    @Value("${my.name}")
    private String name;

    private String url; // expected to be filled automatically

    public String getUrl() {
        return this.url;
    }

    public String getName() {
        return this.name;
    }
}

输出:

...
2017-01-18 15:19:29.720  INFO 4153 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-01-18 15:19:29.724  INFO 4153 --- [           main] com.muatik.Application                   : Started Application in 4.212 seconds (JVM running for 4.937)
null
muatik

这样的执行到底出了什么问题?

编辑和解决方案:可能的重复:Spring Boot@ConfigurationProperties未从环境中检索属性

我发现我错过了ConfigBinder中的setter。添加它们之后,现在就起作用了。

共有1个答案

松嘉运
2023-03-14

您需要从properties类中删除@Component并添加setters,因为@ConfigurationProperties使用了标准bean属性绑定:

@ConfigurationProperties(prefix="my")
public class ConfigBinder {

    private String name;

    private String url; // expected to be filled automatically

    public String getUrl() {
        return this.url;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

并将@EnableConfigurationProperties添加到主类:

@SpringBootApplication
@EnableConfigurationProperties(ConfigBinder.class)
public class Application {

    public static void main(String[] args) {
        final ApplicationContext ctx = SpringApplication.run(Application.class, args);
        final ConfigBinder confs = ctx.getBean(ConfigBinder.class);
        System.out.println(confs.getUrl());
        System.out.println(confs.getName());
    }

}
 类似资料: