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
?
@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
.
You need to create this:
@Component
@ConfigurationProperties(prefix = "server")
public class ServerConfig {
private String host;
private String port;
private String enableLog;
// ... Getter/setter
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With