天天看點

spring應用手冊-IOC(注解實作)-(17)[email protected]注解

戴着假發的程式員出品 抖音ID:戴着假發的程式員 歡迎關注

@Profile注解

spring應用手冊(第二部分)

@Profile注解源碼

package org.springframework.context.annotation;

@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Documented
@org.springframework.context.annotation.Conditional({org.springframework.context.annotation.ProfileCondition.class})
public @interface Profile {
    java.lang.String[] value();
}
           

@Profile和配置檔案的Profile有一樣的作用,就是可以在不同的環境(條件)下讓配置(注冊生效)。

看案例:

/**
 * @author 戴着假發的程式員
 *  
 * @description
 */
@Component
@Profile("oracle")
public class ArticleDAO_oracle implements IArticleDAO {
    public ArticleDAO_oracle(){
        System.out.println("執行個體化ArticleDAO_oracle");
    }
}

/**
 * @author 戴着假發的程式員
 *  
 * @description
 */
@Component
@Profile("mysql")
public class ArticleDAO_mysql implements IArticleDAO {
    public ArticleDAO_oracle(){
        System.out.println("執行個體化ArticleDAO_mysql");
    }
}
           

測試:

/**
 * @author 戴着假發的程式員
 */
public class SpringTest {
    @Test
    public void testAnnotation() throws IOException {
        AnnotationConfigApplicationContext ac =
                new AnnotationConfigApplicationContext();
        //設定啟動環境
        ac.getEnvironment().setActiveProfiles("mysql");
        //注冊掃描包,注冊所有的bean
        ac.scan("com.st");
        //重新整理容器
        ac.refresh();
    }
}
           

測試結果:

執行個體化ArticleDAO_mysql
           

我們發現ArticleDAO_oracle根本就沒有執行個體化。

當然激活環境的方法還有很多。可以參考 XML配置profile章節。