Spring @Conditional based on a value in database table

╄→гoц情女王★ 提交于 2021-02-11 14:15:54

问题


Condition evaluation depends on a value provided in data base table

@Component
public class XYZCondition implements Condition{

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
              //based on value defined in DB should return true/false
    }

}

As Condition is executing very early, unable to fetch db value is there any alternate way to achieve this ?


回答1:


Database values can be changed during application work, while it doesn't seem a good idea to reload application context. So I would recommended using configuration properties to choose which beans should be available in context.

Moreover, there's a Spring Cloud Config that allows you to store configuration in git or some other storages. Its consumers may restart context once configuration changes. It seems worth talking a look at it as well.




回答2:


Hmm, maybe you can just create a Configuration Class and Inject your Repository then create a Bean. Then inside the bean method fetch the value from the database and return conditional instance. something like this

@Configuration
public class Config {

@Autowired  
private Repository repository;

@Bean
public Interface interface(){
  boolean val = reposiory.getDBValue();
  if(val)
    return new Impl1();
  else
    return new Impl2();
  }
}



回答3:


Well, you're trying to do something that doesn't map well to spring boot in this form.

I suggest to slightly change the requirement:

Instead of trying to access the database in the custom condition, create a custom source of configuration and load the property from the database into the Environment so that when the conditionals get evaluated later on during the startup process, the property with an associated value (previously resolved from the database) is already available.

Examples of following such an approach are: - Spring boot cloud config that reads the configuration properties from "remote" config service (via REST) - Spring boot consul integration (that reads from consul obviously)

This approach is much more spring-friendly, and also has can save the application from calling the database multiple times (what if you have 100 beans with this custom conditional) - will it do 100 queries?

Now, this will mean probably that you won't need a custom conditional - probably it will be @Condition on property.

Another caveat is that you won't be able to use JPA/Spring Data to load this property, probably you'll have to go with a Plain JDBC here.



来源:https://stackoverflow.com/questions/61537318/spring-conditional-based-on-a-value-in-database-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!