java - 动态加载配置Bean

标签 java spring spring-security spring-boot oauth-2.0

我正在制作一个 Spring Boot 应用程序,它需要具有基本身份验证或 Oauth2,具体取决于我定义的属性。

问题是,如果我使用 @configuration 创建了两个类,则应用程序不会启动,如果我只留下一个类,并在配置方法中添加一个 if 来配置 HttpSecurity 对象,则在尝试访问端点时会失败具有基本身份验证。

我尝试以这种方式动态注册bean:

@Bean
public ResourceServerSecurityConfig oauthConfig(){
    if(isOauthEnabled){
        return new ResourceServerSecurityConfig();
    }else{
        return null;
    }
}
@Bean
public BasicSecurityConfig basicConfig(){
    if(isOauthEnabled){
        return new BasicSecurityConfig ();
    }else{
        return null;
    }
}

但配置未加载。 关于如何存档的任何提示??

最佳答案

您需要的是有条件的 bean 创建。尝试使用@Conditional。

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Conditional.html

您可以根据系统属性创建自定义条件。

您也可以使用 if 来完成此操作,但其可读性较差,并且会聚集您的配置,但作为一个简短的示例,请尝试以下操作:

@Bean
public SecurityConfig basicConfig(@Value("${authentication.type.oauth}" boolean isOauthEnabled)){
    if(isOauthEnabled){
        return new ResourceServerSecurityConfig();
    }else{
        return new BasicSecurityConfig ();
    }
}

然而,这是一个肮脏的黑客行为。

关于java - 动态加载配置Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37258735/

相关文章:

grails - Grails 2 Spring Core插件-服务器请求基于密码的身份验证,但未指定密码

java - 找到接口(interface) com.google.gwt.core.ext.typeinfo.JClassType,但应为类

java - 如何在 JFrame 中组织我的 JPanel?

java - 帮助使用 Spring 创建图像 servlet

spring - 我们可以为 filterChainProxy 中的单个过滤器链提供多种模式吗

spring-security - Spring Boot 从 LDAP 获取角色

java - Retrofit 2 RequestBody writeTo() 方法调用了两次

java - 根据条件设置 "Java Invocation"部分中的参数

java - 对网络应用程序流口水

spring - 如何在 Spring webflux 应用程序中将 Spring WebSessionIdResolver 与 Spring Security 5 结合使用?