本文实例讲述了Spring条件注解用法。分享给大家供大家参考,具体如下:
一 点睛
Spring 4 提供了一个更通用的基于条件的Bean的创建,即使用@Conditional注解。
@Conditional根据满足仅一个特定条件创建一个特定的Bean。也就是根据特定的条件来控制Bean的创建行为,这样就可以利用这个特性进行一些自动的配置。
二 项目说明
以不同的操作系统为条件,通过实现@Condition接口,并重写matches方法来构造条件。若在windows系统下运行,则输出列表命令为dir;若在Linux操作系统下运行程序,则输出列表命令为ls。
三 实战
1 判断条件定义
1.1 windows的判定条件
package com.wisely.highlight_spring4.ch3.conditional;import org.springframework.context.annotation.Condition;import org.springframework.context.annotation.ConditionContext;import org.springframework.core.type.AnnotatedTypeMetadata;public class WindowsCondition implements Condition { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Windows"); }}
1.2 Linux的判定条件
package com.wisely.highlight_spring4.ch3.conditional;import org.springframework.context.annotation.Condition;import org.springframework.context.annotation.ConditionContext;import org.springframework.core.type.AnnotatedTypeMetadata;public class LinuxCondition implements Condition { public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Linux"); }}
2 不同系统下的Bean类
2.1 接口
package com.wisely.highlight_spring4.ch3.conditional;public interface ListService { public String showListCmd();}
2.2 Window下创建的Bean类
package com.wisely.highlight_spring4.ch3.conditional;public class WindowsListService implements ListService { @Override public String showListCmd() { return "dir"; }}
2.3 Linux下所创建的Bean类
package com.wisely.highlight_spring4.ch3.conditional;public class LinuxListService implements ListService{ @Override public String showListCmd() { return "ls"; }}
3 配置类
package com.wisely.highlight_spring4.ch3.conditional;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Conditional;import org.springframework.context.annotation.Configuration;@Configurationpublic class ConditionConifg { @Bean @Conditional(WindowsCondition.class) //符合window条件,则实例化WindowsListService public ListService windowsListService() { return new WindowsListService(); } @Bean @Conditional(LinuxCondition.class) //符合Linux条件,则实例化LinuxListService public ListService linuxListService() { return new LinuxListService(); }}
4 主类
package com.wisely.highlight_spring4.ch3.conditional;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConditionConifg.class); ListService listService = context.getBean(ListService.class); System.out.println(context.getEnvironment().getProperty("os.name") + "系统下的列表命令为: " + listService.showListCmd()); context.close(); }}
新闻热点
疑难解答