Reputation: 3009
Is it possible to cast a configuration property which is read by SpringBoot from a properties file into a specific class? For instance, having a property
myClass = xx.abc.MyClass
In my configuration class I want to have something like:
private Class myClass = xx.abc.MyClass.class;
Upvotes: 0
Views: 607
Reputation: 3009
I solved the problem by adding a custom converter. Using Type Converters With Spring MVC helped me to find the solution:
import org.springframework.core.convert.converter.Converter;
public class StringToClassConverter implements Converter<String, java.lang.Class> {
@Override
public Class convert(final String source) {
try {
return Class.forName(source);
} catch (ClassNotFoundException cnfEx) {
// Handle exception properly however you want to...
cnfEx.printStackTrace();
}
return null;
}
}
You have your SpringBoot main class let extend WebMvcConfigurerAdapter and implement and implement the register method from WebMvcConfigurerAdapter:
@Override
public void addFormatters(final FormatterRegistry registry) {
registry.addConverter(new StringToClassConverter());
}
Update:
SpringBoot has its own capabilities and it seems top be better to achieve the goal this way:
OR
@see
Spring Boot - Custom Type Conversion with @ConfigurationProperties
and
Spring Boot - Type safe properties binding with @ConfigurationProperties
That's it! :-)
It would be nice that Spring would provide such basic converters out of the box.
Upvotes: 1