我很难从我的属性文件中加载属性。我正在尝试将属性加载到下面列出的配置类中。
package dk.fitfit.budget.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
@Configuration
@PropertySource("classpath:application.properties")
public class ApplicationConfig {
private static final Logger logger = LoggerFactory.getLogger(ApplicationConfig.class);
@Autowired
private Environment env;
@Value("${snot:test}")
private String snot;
public ApplicationConfig() {
logger.info("Application config loaded!"); // Displays as expected
logger.info("snot: {}", snot); // snot: null
logger.info("env: {}", env); // env: null
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
如果我更改文件名 (application.properties) 或“@PropertySource("classpath:application.properties")”,我会收到有关文件不存在的错误消息。很明显它正在加载(无论如何在某种程度上)。
我至少希望看到默认字符串“test”被注入(inject)到变量 snot 中。但甚至还没有完成。我也无法 Autowiring 环境...不确定是否存在关系。
我的application.properties的内容如下。
snot=snog
我的application.properties文件放在src/main/resources/。
有人知道我做错了什么吗?
最佳答案
构造函数的目的是初始化类实例。在 Spring 可以对其执行任何操作之前,您必须构造和初始化类实例。因此,您不能期望 env
和 snot
字段在构造函数中具有除默认 null
值以外的任何值。
关于java - 属性和环境始终为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26455936/