我正在尝试在Spring中实现配置文件,由于某种原因,我不明白我无法将URL从所选配置文件传递给applicartion。 application.yml:
spring:
main:
banner-mode: 'OFF'
profiles:
active: demo_prod
(…)
spring:
profiles: demo_prod
(…)
mUrl: "http://localhost:8081/private/configuration"
BasicConfiguration:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class BasicConfiguration {
@Value("${mURL}")
private static String mURL;
public static String getMURL() {
return mURL;
}
CentralService:
@Service
public class CentralServiceImpl implements CentralServiceAdapter {
private final String URL = BasicConfiguration.getMURL(); //Here debbuging shows URL: null
@Override
public void sendMAttributes(MAttributesDTO mAttributesDTO) throws IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(URL); //Here debbuging shows URL: null
(…)
此URL未传递,邮递员显示错误,断点/调试显示“ URL空”。我做错了什么?似乎未选择配置文件“ demo_prod”或未将指定的URL传递给应用程序。我不知道如何进一步进行。
答案 0 :(得分:0)
首先,这与弹簧轮廓无关。这是基本的弹簧注射。
它不起作用的原因是因为您的变量是静态的。
@Value("${mURL}")
private static String mURL;
就春季而言,静电是邪恶的。尽量避免静电。 Spring不会将值注入静态变量。如果您仍然希望这样做,可以尝试一下。您可以使用设置器方法
private static String mURL;
@Value("${mURL}")
public void setMUrl(String url){
mURL = url;
}
最后(与此问题无关)。使用
时@ConfigurationProperties
避免使用@Value
,这克服了使用ConfigurationProperties的目的