首页 > 代码库 > spring in action学习笔记七:@Conditional注解的用法

spring in action学习笔记七:@Conditional注解的用法

@Profile注解是@Conditional注解的一个例子。即@Profile也是用@Conditional注解来实现的。

必须让条件实现Condition这个接口。

下面的案例讲如果环境中有magic这个属性,则能通过条件,spring会创建bean。反之如果环境中没有magic这个属性,则不能通过条件,spring就不会创建bean,会报错。

案例的代码如下:

MagicBean的代码如下:

 1 package com.advancedWiring.conditionalBeans;
 2 
 3 import org.springframework.beans.factory.BeanNameAware;
 4 import org.springframework.beans.factory.annotation.Value;
 5 
 6 /**
 7  * Created by ${秦林森} on 2017/6/8.
 8  */
 9 public class MagicBean implements BeanNameAware{
10 
11     @Override
12     public void setBeanName(String name) {
13         System.out.println("The MagicBean‘s bean name is :"+name);
14     }
15 }

MagicExistsCondition的代码如下:

 1 package com.advancedWiring.conditionalBeans;
 2 
 3 import org.springframework.context.annotation.Condition;
 4 import org.springframework.context.annotation.ConditionContext;
 5 import org.springframework.core.env.Environment;
 6 import org.springframework.core.type.AnnotatedTypeMetadata;
 7 
 8 /**
 9  * Created by ${秦林森} on 2017/6/8.
10  */
11 public class MagicExistsCondition implements Condition{
12     @Override
13     public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
14         Environment environment = context.getEnvironment();
15         /**
16          * 如果环境包含magic这个属性,则返回true,反之为false
17          * 千万不要理解为MagicBean有magic这个属性返回true,反之为false.
18          */
19         return environment.containsProperty("magic");
20      }
21 }

MapelConfig的代码如下:

 1 package com.advancedWiring.conditionalBeans;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Conditional;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.context.annotation.Import;
 7 
 8 /**
 9  * Created by ${秦林森} on 2017/6/8.
10  */
11 @Configuration
12 public class MapelConfig {
13     @Bean
14     @Conditional(MagicExistsCondition.class)
15     public MagicBean magicBean(){
16         return  new MagicBean();
17     }
18 }

测试类Test的代码如下:

 1 package com.advancedWiring.conditionalBeans;
 2 
 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4 
 5 /**
 6  * Created by ${秦林森} on 2017/6/8.
 7  */
 8 public class Test {
 9     public static void main(String[] args) {
10         /**
11          * 如果想让MagicExistsCondition返回true的话:
12          *  System.setProperty("magic","这里的内容随便写");这句话不能少。
13          *  反之,如果不写上面的语句,则返回false.
14          */
15         System.setProperty("magic","people");//这句话不能少。
16         AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MapelConfig.class);
17         MagicBean magicBean = ac.getBean(MagicBean.class);
18     }
19 }

 

spring in action学习笔记七:@Conditional注解的用法