gpt4 book ai didi

java - ConfigurationProperties 不绑定(bind)属性

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:10:06 26 4
gpt4 key购买 nike

我想通过使用@ConfigurationProperties 注释将我的application.properties 自动绑定(bind)到一个类中。首先,我尝试使用 @Value 注释,并且能够将属性值注入(inject)到类变量中。但是,@ConfigurationProperties 没有将属性注入(inject)到值中。

我的应用程序.properties:

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

应用程序.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 not retrieving properties from Environment

我发现我错过了ConfigBinder中的setter。添加它们后,它现在可以工作了。

最佳答案

您需要从属性类中删除@Component 并添加setter,因为@ConfigurationProperties 使用标准bean 属性绑定(bind):

@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());
}

}

关于java - ConfigurationProperties 不绑定(bind)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41719466/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com