spring配置文件详解_Spring配置文件简介

spring配置文件详解

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配置文件详解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值