Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

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?

like image 574
Niranjan Avatar asked Mar 30 '16 10:03

Niranjan


2 Answers

@Bean({"kaptchaProperties"})
@ConfigurationProperties(prefix = "custom.kaptcha")
public Properties getProperties() {
    return new Properties();
}
like image 129
loocao Avatar answered Oct 24 '22 10:10

loocao


AFAIK, you can't load them into java.util.Properties with annotation @ConfigurationProperties.

You need to create this:

@Component
@ConfigurationProperties(prefix = "server")
public class ServerConfig {
  private String host;
  private String port;
  private String enableLog;
  // ... Getter/setter
}
like image 22
luboskrnac Avatar answered Oct 24 '22 12:10

luboskrnac