Spring配置文件默认行为

Spr*_*ing 5 java spring spring-security

我有一个弹簧配置文件"DEV",这是我唯一的配置文件,我不想创建一个"生产"配置文件.因此,只有当配置文件是"DEV"时,我才会启动某种类型的bean用于Spring安全性(这是一个内存来宾用户和一个userdetails bean)

但是如果我的tomcat启动中没有提供spring配置文件(生产中就是这种情况),我希望我的应用程序继续它已经在做的事情(使用ldap authenticatin提供程序).

有没有办法定义"默认"bean行为而不需要在启动时提供配置文件?或者您可以查看下面的代码,并提出一个不同的解决方案.

@Autowired
public void configureGlobal(final AuthenticationManagerBuilder auth, final AuthenticationProvider provider) throws Exception {

        auth
                .eraseCredentials(false)
                .authenticationProvider(provider)
                .authenticationProvider(jwtConfig.jwtAuthenticationProvider());
}


@Bean
public UserDetailsService userDetailsService() {
    final LdapUserDetailsService ldapUserDetailsService = new LdapUserDetailsService(ldapUserSearch(), ldapAuthoritiesPopulator());
    return new CompositeUserDetailsService(Arrays.asList(technicalUserDetailsService(), ldapUserDetailsService));
}

@Bean
@Profile("DEV")
public UserDetailsService devUserDetailsService() {
 useAnonymous = true;
        InMemoryUserDetailsManagerBuilder b = new InMemoryUserDetailsManagerBuilder()
                .withUser("user").password("password").authorities(ROLE_USER, ROLE_ADMIN).and();

        return new CompositeUserDetailsService(Arrays.asList(b.build(),
                technicalUserDetailsService()));

}
@Bean
public AuthenticationProvider ldapAuthenticationProvider() {
    final BindAuthenticator ba = new BindAuthenticator((BaseLdapPathContextSource) contextSource());
    ba.setUserSearch(ldapUserSearch());
    return new LdapAuthenticationProvider(ba, ldapAuthoritiesPopulator());
}
Run Code Online (Sandbox Code Playgroud)

joh*_*384 6

我认为存在误解的原因@Profile.标记为的Bean @Profile仅在该配置文件处于活动状态时加载,但@Profile无论选择的配置文件如何,所有其他bean(不带a )仍始终加载.

我看到几种解决方法:

1)标记所有那些豆子用@Profile("dev")@Primary使Spring知道当两个相同类型的bean被装载哪一个选择(因为你DONOT要使用生产配置文件).

2)标志应该豆子不能当轮廓dev的是活动的,要加载@Profile("!dev")-仅适用于春季3.2和更高版本(见https://github.com/spring-projects/spring-framework/commit/bcd44f3798ed06c0704d2a3564b8a9735e747e87).

要么...

3)使用生产配置文件并简单地在例如web.xml文件(您可能不在本地使用的东西)中激活它.

只需创建多个@Configuration类并使用配置文件标记整个类(它还有助于将相关内容保持在一起).典型的例子是数据库.为生产数据库(使用JNDI和Oracle)创建一个配置类,为本地开发和测试(HSQLDB)创建一个配置类.

使用@Profile("production")和另一个 标记JNDI配置类@Profile("dev")- 不需要标记单个bean,只需在逻辑上将它们分成两个不同的@Configuration类.

这对我们来说非常有效,当与集成测试结合使用时也是如此.