Read spring properties from consuming applications
I’m working on a Java library/package designed to be used as a jar by Spring Boot applications.
The main driver class relies on a set of props present in applicaton.properties and defines its own collection in the repository.
However, I expect these properties to be configurable by using the app. What is the correct way to build this?
For example, I have a file in the project
public class Properties {
private int maxConnectingCount;
private int maxIdleCount;
// .. other properties read from application.properties
}
The main driver class looks like this:
public class LibraryDriver {
@Autowired
private Properties props
do stuff with these props
}
How can I make the consuming app override these properties
Solution
This is what I usually do:
public class Properties {
private int maxConnectingCount;
private int maxIdleCount;
public Properties(String maxConnectingCount, String maxIdleCount) {
this.maxConnectingCount = maxConnectingCount;
this.maxIdleCount = maxIdleCount;
}
}
Then create bean:: like this
@Configuration
public class LibraryDriverConfiguration {
@Value("${maxConnectingCount}")
private int maxConnectingCount;
@Value("${maxIdleCount}")
private int maxIdleCount;
@Bean
LibraryDriver libraryDriver() {
return new LibraryDriver(new Properties(maxConnectingCount, maxIdleCount));
}
I like this approach because it allows your properties to have reasonable default values by defining different constructors.
Another option is to create a Property
bean and then Autowire it to the LibraryDriver
; Something like this:
@Configuration
public class PropertiesConfiguration {
@Value("${maxConnectingCount}")
private int maxConnectingCount;
@Value("${maxIdleCount}")
private int maxIdleCount;
@Bean
Properties properties() {
return new Properties(maxConnectingCount, maxIdleCount);
}
}
And then:
@Component
public class LibraryDriver {
private final Properties properties;
@Autowired
public LibraryDriver(Properties properties) {
this.properties = properties;
}
}