简体   繁体   中英

@ConditionalOnBean does not work with manually registered bean

I have such an issue. On the basis of the database configuration I need to create appropriate beans that will handle whole process. I've figured out that I will try do it in the following way. First, create the marker bean on the basis of db config .

@Configuration
class Dbconfig {
  @Autowired DbRepo dbRepo;
  @Autowired GenericApplicationContext applicationContext;
  @PostConstruct
  public void init(){
    Config config = dbRepo.findConfiguration();
    if(config.value.equals("test")){
      applicationContext.registerBean("testBean", TestBean.class, TestBean::new);
    }else{ //other steps
  }
}

Then, on the basis of this marker bean I will create the proper ones, like:

@Configuration
@ConditionalOnBean(name = "testBean")
@AutoConfigureAfter(value = Dbconfig.class)
public class ObjConfig{
//creating proper @Beans
  }

But, unfortunately, it does not work. Don't know why spring does not seem to see this “testBean”. Nevertheless, I have debugged it and I can see this bean exists in BeanFactory of the Application Context. It also works smoothly with the @DependsOn annotation, then spring can see this bean. I will appreciate any help or suggestions how to resolve the problem in other way.

@AutoConfigureAfter will only work on an auto-configuration class and not for manually configured beans. If you were wiring testBean as a Autowired bean your code will work. You may try @ConditionalOnExpression to inject bean based on an SpEL expression.

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