简体   繁体   中英

Opposite of ConditionalOnMissingBean

So I have a standard Spring Boot web application. And I have a requirement to allow multiple authentication mechanisms. So I want to be able to have jar files that handle different authentication. One for a SAML server, CAS, OAuth, etc...

I want my "base" war file to use standard jdbc (Which it does now) but I want to be able to put my, say, CAS-security.jar in the classpath and have spring use it's AuthenticationProvider. Right now I have this in my Application.java class

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
    .authenticationProvider(authenticationProvider)
    .userDetailsService(userDetailsService);
}

And I @Autowire the provider and service, which are defined as @Bean as normal...

But I want to annotate (I think) those @Bean definitions to say "Don't use this if there is another one avail"

I want the exact opposite of ConditionalOnMissingBean. Now I suppose I could use that annotation, and list every possible plugin class that I could use, but that is bad form as I don't want to recompile/redeploy every time I create a new security plugin.

Is there a UseThisIfNoOtherBeanExists type annotation?

In fact, what I really want, is that I have ALL of my security stuff in say, SecurityConfiguration, annotated with @Configuration, and have the whole class replaced with something else if available.

Sounds like you're looking for ConditionalOnMissingBean . A bean annotated with this will only be used if and only if a bean of its type is not already registered in the bean factory.

If you're somehow not satisfied with that, you have options. You can peruse the entire org.springframework.boot.autoconfigure.condition package to see if there's something there that best fits your use case. Alternatively, you could also leverage @Conditional , and hand-craft a condition based on the environment your application is running in.

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