java – Spring配置文件的默认行为
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Spring配置文件的默认行为,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2624字,纯文字阅读大概需要4分钟。
内容图文
我有一个弹簧配置文件“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());
}
最佳答案:
我认为对@Profile的作用存在误解.标记为@Profile的Bean仅在该配置文件处于活动状态时加载,但所有其他bean(没有@Profile)仍然始终加载,无论选择的配置文件如何.
我看到几种解决方法:
1)使用@Profmary标记所有那些带有@Profile(“dev”)的bean,因此Spring知道在加载两个相同类型的bean时要选择哪一个(因为你不想使用生产配置文件).
2)使用@Profile(“!dev”)标记在配置文件dev处于活动状态时不应加载的bean – 仅适用于Spring 3.2及更高版本(请参阅https://github.com/spring-projects/spring-framework/commit/bcd44f3798ed06c0704d2a3564b8a9735e747e87).
要么…
3)使用生产配置文件并在例如web.xml文件(您可能不在本地使用的东西)中激活它.
只需创建多个@Configuration类并使用配置文件标记整个类(它还有助于将相关内容保存在一起).典型的例子是数据库.为生产数据库(使用JNDI和Oracle)创建一个配置类,为本地开发和测试(HSQLDB)创建一个配置类.
使用@Profile(“production”)标记JNDI Configuration类,使用@Profile(“dev”)标记另一个类 – 不需要标记单个bean,只需在逻辑上将它们分成两个不同的@Configuration类.
这对我们来说非常有效,当与集成测试结合使用时也是如此.
内容总结
以上是互联网集市为您收集整理的java – Spring配置文件的默认行为全部内容,希望文章能够帮你解决java – Spring配置文件的默认行为所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。