我有一个 Spring Web 应用程序,我正在尝试将 YAML 配置文件加载到 Java 配置类中。但是,我的配置类在我的 JUnit 测试中实例化后仅包含空成员变量。我是 Spring 新手,可能错过了一些明显的东西。我用 Maven 构建了这个项目,并拥有一个 Maven 风格的目录树。
我的配置Java类:
src/main/java/com/my/package/config/YAMLConfigDatabase:
package com.my.package;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "database")
public class YAMLConfigDatabase {
private String url;
private int port;
private String schema;
private String username;
private String password;
//Getters and setters are all here.
}
我的配置 YAML 文件:
src/main/resources/application.yml
server.port: 8090
database:
url: 'localhost'
port: 3306
schema: 'my_schema'
username: 'webappuser'
password: 'secretPassword'
我的 JUnit 测试检查我是否确实可以加载配置文件:
package com.my.package;
import com.my.package.config.YAMLConfigDatabase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {YAMLConfigDatabase.class})
public class YAMLConfigTest {
private YAMLConfigDatabase config;
@Autowired
public void setYAMLConfigDatabase(YAMLConfigDatabase config){
this.config = config;
}
@Test
public void isYAMLConfigLoaded(){
System.out.println(this.config);
System.out.println(this.config.getPassword());
//The above line returns "null", but I would like it to return "secretPassword".
}
}
编辑:
我改变了我YAMLConfigDatabase.java
的样子:
package com.my.package.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "database")
@PropertySource(value = "classpath:application.yml") //new line
@Component
public class YAMLConfigDatabase {
@Value("${url}") //new line
private String url;
@Value("${port}") //new line
private Integer port;
@Value("${schema}") //new line
private String schema;
@Value("${username}") //new line
private String username;
@Value("${password}") //new line
private String password;
}
我使用Senior Promidor 技巧将@Value 注解添加到所有成员变量中,并且我还必须添加行@PropertySource(value = "classpath:application.yml")
。如果我跳过后一步,@Value 注释中的参数将按字面意思解释,正如我在评论中提到的那样。