0

Currently, I have a service class within which I am trying to constructor auto wire Configuration class. However, I would expect my service class to be generic and work for any Configuration class with similar properties. Is there a way I can conditionally auto wire configuration class in the service class based on parameter. I don't want any if-else condition. Below is my sample code snippet

    @Service
    public ServiceClass {
    private COnfigurationClass configurationClass

    public ServiceClass(COnfigurationClass configurationClass) {
       this.configurationClass = configurationClass
    }

    //Some method that makes use of configuration class

    }

    @ConfigurationProperties(prefix="abc")
    public class COnfigurationClass {
      enter code here
    }

I want my ServiceClass to auto wire new ConfigurationClass with prefix="xyz" based on parameter i pass while initializing ServiceClass

  • Is this what you are looking for ? https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Profile.html . @Profile helps you create a bean based on the profile active. – R.G Jan 23 '20 at 07:19

2 Answers2

0

Ok I was able to solve this. I created a base Class which was extended by multiple Configuration class which all had the same config properties.

Now I autowire all config classes as List

Below is my example

@Component
public class BaseConfig {

}

@Component
@ConfigurationProperties(prefix="abc")
public class ConfigABC extends BaseConfig {

}

@Component
@ConfigurationProperties(prefix="xyz)
public class ConfigXYZ extends BaseConfig {

}



@Service
public SomeService {

@Autwire
List<BaseConfig> baseConfig; //baseConfig contains the list of all BaseConfig classes

baseConfig.checkForSomeProperty() //Determine which config property to use

}

}


0

so a simple solution would be to add a annotation of @ConditionalOnProperty(value = "bean.enabled") on the method where your bean is being created (configurationClass bean)

and while autowiring it in your service class use @Autowired(required=false) though you will have to do null check later while using

refer to the similar question which could help, How to Autowire conditionally in spring boot?