![spring配置文件详解](https://i-blog.csdnimg.cn/blog_migrate/8f87f87618eba37e764265122976f00e.png)
spring配置文件详解
这么多的人,那么多的思想。 当我们为不同的客户实施软件时,有时我们需要处理同一项目的各种需求。 例如,客户A需要SAML身份验证,客户B需要LDAP身份验证。
使用Spring Profiles(可从Spring 3.1获得),我们能够提供一种方法来隔离我们已实现的应用程序配置的各个部分。 该博客将帮助我们提供某些代码或仅适用于特定要求的某些Spring bean。 例如,当使用Spring Security时,此博客中使用的示例可用于为提供者管理器激活所需的身份验证提供者。
可以通过注释和/或xml配置配置文件。
注解
@Component或@Configuration注释的Bean可以包含注释@Profile,以仅在特定环境中加载它们。
LDAP概要文件注释的配置
@Component
@Profile("ldap")
public class LDAPAuthentication {
public LDAPAuthentication() {
System.out.println("LDAP Authentication set by annotations");
}
}
Saml配置文件注释的配置
@Component
@Profile("saml")
public class SAMLAuthentication {
public SAMLAuthentication() {
System.out.println("SAML Authentication set by annotations");
}
}
XML格式
在刚开始的项目中可能不再使用,但也可以使某些Spring bean仅在XML配置中可用。
Spring XML配置
<!--
We use the profile attribute on the beans element to specify the profile.
Only the child beans are loaded on initialization if the profile is active
-->
<beans profile="ldap">
<bean class="com.jdriven.blog.profiles.xml.LDAPAuthentication" />
</beans>
<beans profile="saml">
<bean class="com.jdriven.blog.profiles.xml.SAMLAuthentication" />
</beans>
激活正确的个人资料
当然,您可以组合两种配置,但是显而易见的是选择一种配置以使代码更可预测。 只是为了展示我们将它们组合在一个项目中的可能性。在普通的Java应用程序中,可以通过在应用程序上下文中激活配置文件来设置配置文件。
运行示例应用程序
public static void main(String[] args) {
//Create new context to show the XML Spring profile setup
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
//Setting 'ldap' as active profile
ctx.getEnvironment().setActiveProfiles("ldap");
//Load the app-context.xml from the root of the classpath
ctx.load("classpath:app-context.xml");
//We need to refresh the application because we added a resource
ctx.refresh();
//Closing the application context to release and destroy all resources and cached beans
ctx.close();
//Creating a new context to show the annotation Spring profile setup
AnnotationConfigApplicationContext actx = new AnnotationConfigApplicationContext();
//Setting 'saml' as active profile
actx.getEnvironment().setActiveProfiles("saml");
//Scan base package for annotations
actx.scan("com.jdriven.blog");
//We need to refresh the application because we added a scan
actx.refresh();
//Closing the application context to release and destroy all resources and cached beans
actx.close();
}
有关此项目的完整源代码,请参见以下github:
翻译自: https://www.javacodegeeks.com/2015/03/introduction-to-spring-profiles.html
spring配置文件详解