du-it
du-it

Reputation: 3009

Can I cast a value in a properties file using SpringBoot configuration?

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

Answers (1)

du-it
du-it

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:

  1. Annotate the Converter with
    @Component and
    @ConfigurationPropertiesBinding

OR

  1. Use @EnableConfigurationProperties(MyAppProperties.class) along with @SpringBootApplication

@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

Related Questions