This Spring Boot app creates the GreetingService bean only if the property app.greeting.enabled is set to true in application.properties. The main method checks if the bean exists and prints the result.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
var context = SpringApplication.run(DemoApplication.class, args);
boolean hasBean = context.containsBean("greetingService");
System.out.println("Is GreetingService bean created? " + hasBean);
}
@Bean
@ConditionalOnProperty(name = "app.greeting.enabled", havingValue = "true")
public GreetingService greetingService() {
return new GreetingService();
}
public static class GreetingService {
public String greet() {
return "Hello!";
}
}
}