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

时间:2016-03-30 10:03:00

标签: java spring spring-boot

在我的春季启动应用程序中,我有以下配置:

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

我想将上述内容翻译为java.util.Properties。我尝试过以下课程:

@ConfigurationProperties(prefix = "server")
public class ServerConfig {
  private Properties serverProps;
  // ... Getter/setter
}

启动配置文件如下所示:

@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

我不确定为什么会这样。我想到的唯一想法是,server下面的配置参数基本上是扁平字符串。我有什么办法可以把它们看作Properties吗?

2 个答案:

答案 0 :(得分:1)

AFAIK,您无法使用注释java.util.Properties将其加载到@ConfigurationProperties

你需要创建这个:

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

答案 1 :(得分:1)

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