simon
simon

Reputation: 12922

Spring Boot: use autowired constructor with class from configuration file

I have a Spring Boot 2.3 application with a controller:

@RestController
public class StatusController {

    private final ServerStatusCheck serverStatusCheck;
    private final ServerStatusMapper serverStatusMapper;

    @Autowired
    public StatusController(AService aService, ServerStatusMapper serverStatusMapper) {
        this.serverStatusCheck = aService;
        this.serverStatusMapper = serverStatusMapper;
    }

    // (...)
}

The class AService implements the interface ServerStatusCheck. There is also a BService class, also implementing ServerStatusCheck interface.

What I need to do: the injected AService object should be configurable in a configuration file, so that the service injected is either "AService" or "BService", depending on the configuration file values. What is the best way to achieve this using Spring Boot? If possible, I would like to keep the constructor-based autowiring (instead of field-based autowiring).

Upvotes: 0

Views: 263

Answers (1)

Devilluminati
Devilluminati

Reputation: 338

You can create the different beans in a configuration class with condition like https://reflectoring.io/spring-boot-conditionals/

@Configuration
public class ServiceConfiguration {

   @ConditionalOnProperty(value="service.a.enabled", havingValue = "true", matchIfMissing = true)
   public ServerStatusCheck serverStatusCheckA() {
      return new AService();
   }

   @ConditionalOnMissingBean
   @ConditionalOnProperty(value="service.b.enabled", havingValue = "true", matchIfMissing = true)
   public ServerStatusCheck serverStatusCheckB() {
      return new BService();
   }
}

and then wire the bean into the constructor

Upvotes: 1

Related Questions