2.17@Profile注解

戴着假发的程序员出品  抖音ID:戴着假发的程序员  欢迎关注

[查看视频教程]

1 package org.springframework.context.annotation;
2 
3 @java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD})
4 @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
5 @java.lang.annotation.Documented
6 @org.springframework.context.annotation.Conditional({org.springframework.context.annotation.ProfileCondition.class})
7 public @interface Profile {
8     java.lang.String[] value();
9 }

@Profile和配置文件的Profile有一样的作用,就是可以在不同的环境(条件)下让配置(注册生效)。

看案例:

 1 /**
 2  * @author 戴着假发的程序员
 3  *  
 4  * @description
 5  */
 6 @Component
 7 @Profile("oracle")
 8 public class ArticleDAO_oracle implements IArticleDAO {
 9     public ArticleDAO_oracle(){
10         System.out.println("实例化ArticleDAO_oracle");
11     }
12 }
13 
14 /**
15  * @author 戴着假发的程序员
16  *  
17  * @description
18  */
19 @Component
20 @Profile("mysql")
21 public class ArticleDAO_mysql implements IArticleDAO {
22     public ArticleDAO_oracle(){
23         System.out.println("实例化ArticleDAO_mysql");
24     }
25 }

测试:

 1 /**
 2  * @author 戴着假发的程序员
 3  */
 4 public class SpringTest {
 5     @Test
 6     public void testAnnotation() throws IOException {
 7         AnnotationConfigApplicationContext ac =
 8                 new AnnotationConfigApplicationContext();
 9         //设置启动环境
10         ac.getEnvironment().setActiveProfiles("mysql");
11         //注册扫描包,注册所有的bean
12         ac.scan("com.st");
13         //刷新容器
14         ac.refresh();
15     }
16 }

测试结果:

实例化ArticleDAO_mysql

我们发现ArticleDAO_oracle根本就没有实例化。

当然激活环境的方法还有很多。可以参考 XML配置profile章节。

posted @ 2020-10-10 08:23  戴着假发的程序员0-1  阅读(176)  评论(0编辑  收藏  举报