在 spring boot 中如何将 yml 部分加载为 java.util.Properties [英] In spring boot how to load a yml section as java.util.Properties
问题描述
在我的 spring boot 应用程序中,我有以下配置:
In my spring boot application, I have following configuration:
server:
host: a.com
port: 5922
enable-log: true
我想将上述内容作为 java.util.Properties
阅读.我试着把下面的课:
I want to read the above as a java.util.Properties
. I tried putting following class:
@ConfigurationProperties(prefix = "server")
public class ServerConfig {
private Properties serverProps;
// ... Getter/setter
}
启动配置文件如下所示:
The boot config files look like:
@Configuration
@ComponentScan("com.demo")
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableConfigurationProperties({ServerConfig.class})
@Profile({"dev"})
public class TestAppConfiguration {
}
@EnableAutoConfiguration
@SpringBootApplication
public class TestAppInitializer {
public static void main(final String[] args) {
SpringApplication.run(TestAppInitializer.class, args);
}
}
单元测试类:
@SpringApplicationConfiguration(classes = {TestAppInitializer.class})
@ActiveProfiles("dev")
public class ServerConfigTest extends AbstractTestNGSpringContextTests {
@Autowired
private ServerConfig serverConfig;
@Test
public void printDetails() {
logger.debug("ServerConfig.properties --> {}", serverConfig.getProperties());
}
}
输出是ServerConfig.properties -->null
.
The output is
ServerConfig.properties --> null
.
我不确定为什么会发生这种情况.我想到的唯一想法是,server
下面的配置参数基本上是扁平字符串.有什么办法可以将它们读作 Properties
吗?
I am not sure why is this happening. The only idea that comes to my mind is, the configuration parameters underneath server
are basically flat strings. Is there any way I can read those as Properties
?
推荐答案
AFAIK,您无法使用注释 @ConfigurationProperties
将它们加载到 java.util.Properties
中.
AFAIK, you can't load them into java.util.Properties
with annotation @ConfigurationProperties
.
你需要创建这个:
@Component
@ConfigurationProperties(prefix = "server")
public class ServerConfig {
private String host;
private String port;
private String enableLog;
// ... Getter/setter
}
这篇关于在 spring boot 中如何将 yml 部分加载为 java.util.Properties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!