javascript
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 setupGenericXmlApplicationContext ctx = new GenericXmlApplicationContext();//Setting 'ldap' as active profilectx.getEnvironment().setActiveProfiles("ldap");//Load the app-context.xml from the root of the classpathctx.load("classpath:app-context.xml");//We need to refresh the application because we added a resourcectx.refresh();//Closing the application context to release and destroy all resources and cached beansctx.close();//Creating a new context to show the annotation Spring profile setupAnnotationConfigApplicationContext actx = new AnnotationConfigApplicationContext();//Setting 'saml' as active profileactx.getEnvironment().setActiveProfiles("saml");//Scan base package for annotationsactx.scan("com.jdriven.blog");//We need to refresh the application because we added a scanactx.refresh();//Closing the application context to release and destroy all resources and cached beansactx.close(); }有關此項目的完整源代碼,請參見以下github:
- https://github.com/michelmeeuwissen/Spring-Profiles-Intro
翻譯自: https://www.javacodegeeks.com/2015/03/introduction-to-spring-profiles.html
總結
以上是生活随笔為你收集整理的Spring配置文件简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自采暖是什么意思 自采暖解释
- 下一篇: 什么是 最外层电子数 最外层电子数简单介