简体   繁体   中英

@ConditionalOnProperty annotation not working in spring boot project

I want to conditionally create a spring bean. I figured @ConditionalOnProperty would serve that purpose. I used it in my service class but I do not see the bean being created.

Here is my bean that I want to be conditionally created

@Service
@ConditionalOnProperty(value = "polling.enabled", havingValue = "true")
public class MessageQueueService {

@Scheduled(fixedDelay = INTERVAL_MS)
    public void execute() {
     //sysout
    }
}

couple of thing to note.

-- our service loads properties directly from consul(due to legacy reasons) and not through spring environment

-- I hacked RestTemplate bean (below) to add custom propertyResource into environment. I did not know how to do it without creating another PropertySource bean instance.

@Configuration
public class AppConfig {

@Autowired
ConfigurableEnvironment env;

@Bean(name = "consulProps")
 public Properties properties() {
     Properties consulProperties = new ConsulDriver(env.getConsulUrl()).loadProperties();
    return properties;
 }

@Bean
@Autowired
public RestTemplate restTemplate(@Qualifier(consulProps) Properties props) {
    MutablePropertySources sources = env.getPropertySources();
    sources.addFirst(pollingEnabled(props));
    return new RestTemplate();
    }

private MapPropertySource pollingEnabled(Properties props) {
     String enabled = props.getProperty("polling.enabled"); // line 25
     Map<String, Object> map = new HashMap<>();
     if (StringUtils.isNotBlank(enabled)) {
           map.put("polling.enabled", enabled);
     }
     else {
          map.put("polling.enabled", "false");
     }
       return new MapPropertySource("polling", map);
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

when I run the service, it starts up. I have set up polling.enabled is true in consul. while debugging, I confirmed the value is set correctly in line 25. However, the bean is NOT created. if I comment-out the @ConditionalOnProperty from the class, bean is created and the scheduled Method is called.

Any help to fix this is highly appreciated!! Thanks in advance

This did the work for me (Kotlin, but Java works exactly the same)

@Configuration
class ConditionalBeanConfig {

@Bean
@ConditionalOnProperty(name=["modbus.modbushelper"], havingValue="simulate")
fun conditionalModBusHelper(): ModBusApi {
   return  ModBusSimulatorImpl()
}

@Bean
@ConditionalOnProperty(name=["modbus.modbushelper"],     
havingValue="normal",matchIfMissing = true)
fun conditionalModBus(): ModBusApi {
   var modBusImpl:ModBusApi =  ModBusHelperImpl(Helper())
    return modBusImpl
}

}

interface ModBusApi {

    fun getModbusRegisterValue(startingAddress: Int, quantity: Int): String?

    fun setModbusSingleRegisterValue(startingAddress: Int, value: Int)

}  

class ModBusSimulatorImpl : ModBusApi {

 override fun getModbusRegisterValue(startingAddress: Int, quantity: Int): String? 

   ...

override fun setModbusSingleRegisterValue(startingAddress: Int, value: Int){
  
....

in combi with application.properties:

#simulate, normal
modbus.modbushelper=simulate

Make sure, you have, like always, your packaging in good health:

-Application starts with rootpackage.App

-All your objects/modules start with rootpackage.....

Spring CDI @ComponentScan is is very picky on that, and follows security Java conventions. If you dont, you can experience wide variety of CDI problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM