我有一个 spring 配置文件“DEV”,这是我唯一的配置文件,我不想创建“生产”配置文件。因此,只有当配置文件为“DEV”时,我才会启动某种类型的用于 spring 安全的 bean(这是一个内存中的 guest 用户和一个 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());
}
最佳答案
我觉得有什么误解@Profile
做。标有 @Profile
的 bean 类仅在该配置文件处于 Activity 状态时加载,但所有其他 bean(没有 @Profile
)仍然始终加载,无论选择的配置文件如何。
我看到了一些解决这个问题的方法:
1) 用 @Profile("dev")
标记所有这些 bean 还有 @Primary
所以 Spring 知道在加载两个相同类型的 bean 时选择哪一个(因为您不想使用生产配置文件)。
2) 用 @Profile("!dev")
标记当 profile dev 处于 Activity 状态时不应不加载的 bean| -- 仅适用于 Spring 3.2 及更高版本(参见 https://github.com/spring-projects/spring-framework/commit/bcd44f3798ed06c0704d2a3564b8a9735e747e87 )。
或者...
3) 使用生产配置文件并在例如 web.xml
中简单地激活它文件(您可能不会在本地使用的东西)。
简单地创建多个@Configuration
类并用配置文件标记整个类(这也有助于将相关内容放在一起)。一个典型的例子是数据库。为生产数据库(JNDI 和 Oracle)创建一个配置类,为本地开发和测试(HSQLDB)创建一个配置类。
您将 JNDI 配置类标记为 @Profile("production")
另一个是@Profile("dev")
-- 无需标记单个 bean,只需将它们逻辑地分成两个不同的 @Configuration
类。
这对我们来说非常有效,在与集成测试结合时也是如此。
关于java - Spring 配置文件默认行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43253164/