Home > Software engineering >  How to Autowired an instance of a subclass based on a property that is defined in property file
How to Autowired an instance of a subclass based on a property that is defined in property file

Time:03-26

I use SpringBoot 2.2.2.RELEASE (pretty old one) and I have the following requirements:

I have a @Service class, which I would like to expand its constructor by adding an interface. When the application loads I would like the correct instance of the interface to be @Autowired based on some property I would define in a property file. so this is basically a Factory which instantiate classes by some property that defined in property file.

Here is a snippet of how I would imagine it to work:

@Service
class MyService {

   @Autowired
   public MyService(Shape shape) { ...}
}


interface Shape { ...}

class Circle implements Shape { ... }

class Rectangle implements Shape { ... }

The magic should resides in some Factory class that reads a property from property file and accordingly instantiate one of the subclasses of Shape.

Each instance of this application runs on a dedicated machine (EC2) with its own unique property files.

Is there something like this built into Spring Boot?

Any suggestions would be appreciated!

CodePudding user response:

One way to achieve it is to use @ConditionalOnProperty annotation to instantiate beans when properties have a specific value. You could use matchIfMissing = true to determine default behavior.

@Bean
@ConditionalOnProperty(name = "shape", havingValue = "circle", matchIfMissing = true)
public Shape circleShape() {
    return new Circle();
}

@Bean
@ConditionalOnProperty(name = "shape", havingValue = "rectangle")
public Shape rectangleShape() {
    return new Rectangle();
}
  • Related