简体   繁体   English

在spring boot中如何将yml部分加载为java.util.Properties

[英]In spring boot how to load a yml section as java.util.Properties

In my spring boot application, I have following configuration: 在我的春季启动应用程序中,我有以下配置:

server:
  host: a.com
  port: 5922
  enable-log: true

I want to read the above as a java.util.Properties . 我想将上面的内容读作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);
  }
}

Unit test class: 单元测试类:

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

The output is ServerConfig.properties --> null . 输出是ServerConfig.properties --> null

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. 我想到的唯一想法是, server下的配置参数基本上是扁平字符串。 Is there any way I can read those as Properties ? 有什么方法可以把它们看作Properties吗?

@Bean({"kaptchaProperties"})
@ConfigurationProperties(prefix = "custom.kaptcha")
public Properties getProperties() {
    return new Properties();
}

AFAIK, you can't load them into java.util.Properties with annotation @ConfigurationProperties . AFAIK,您无法将它们加载到带有注释@ConfigurationProperties java.util.Properties

You need to create this: 你需要创建这个:

@Component
@ConfigurationProperties(prefix = "server")
public class ServerConfig {
  private String host;
  private String port;
  private String enableLog;
  // ... Getter/setter
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM