@ConditionalOnProperty Annotation on Spring boot
- Manbodh ratre
- Aug 5, 2024
- 2 min read
This annotation is help to create bean based on condition using some property , it is a class level annotation , to create a bean we can use this code
@ConditionalOnProperty(prefix = "carservice1", value = "enabled", havingValue = "true", matchIfMissing = false)
to create s bean of this class we have to add a property in application.property file
prefix.value is a key and havingValue is value of key
and if value is miss-matched then bean will not be created due to matchIfMissing = false
example: carservice1.enable = true
this value should match with havingValue field then only the bean will be created
let's understand this using code example
// let's suppose i want to create two service and both service has implemented the common method createCar(). and i want to call a method of any service
// Car Service Interface
public interface CarService {
public void createCar();
}
@Component
@ConditionalOnProperty(prefix = "carservice1", value = "enabled", havingValue = "true", matchIfMissing = false)
public class Service1 implements CarService{
public Service1() {
System.out.println("Service1 created");
}
@Override
public void createCar(){
System.out.println("Car is created by service1");
}
}@Component
@ConditionalOnProperty(prefix = "carservice2", value = "enabled", havingValue = "true", matchIfMissing = false)
public class Service2 implements CarService {
public Service2() {
System.out.println("Service2 is created");
}
@Override
public void createCar() {
System.out.println("Car is created by service2");
}
}// in this CreateCarService i wanted to inject Service1 and Service2 using autowired annotation
here i have added attribute required = false so it will not throw an error when bean is not found
@Service
public class CreateCarService {
@Autowired(required = false)
private Service1 carService1;
@Autowired(required = false)
private Service2 carService2;
@PostConstruct
public void init() {
System.out.println("init method");
System.out.println("Service1: " + carService1);
System.out.println("Service2: " + carService2);
}
public CarService getCarService() {
if (carService1 != null) {
return carService1;
} else if (carService2 != null) {
return carService2;
} else {
throw new IllegalStateException("No CarService implementation available");
}
}
}Main Method to user this implementation
public static void main(String[] args) {
CreateCarService createCarService = new CreateCarService();
CarService carService = createCarService.getCarService();
carService.createCar();
}note : before using this code we have to add property then only service1 bean will be created
carservice1.enable=true
Output: Car is created by service1







Comments