一 .概述
在spring之中提供@Conditional注解完成条件注入.
我们可以实现特定的接口,完成配置类可以根据条件进行Bean的创建.
二 .测试
public abstract class OS { protected String name; public String getName() { return this.name; } } class Windows extends OS { public Windows() { super.name = "windows"; } } class Linux extends OS { public Linux() { super.name = "linux"; } }
配置类:
@Configuration public class ConditionalConfig { @Bean//只用条件成立才会创建对象 @Conditional(WindowsConditonal.class) public OS windows() { return new Windows(); } @Bean @Conditional(LinuxConditional.class) public OS linux() { return new Linux(); } }
两个条件类:
public class AbstractConditional { public String getOSName(ConditionContext context) { Environment environment = context.getEnvironment(); String osName = environment.getProperty("os.name"); return osName; } }
public class WindowsConditonal extends AbstractConditional implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { if(super.getOSName(context).toUpperCase().contains("WINDOWS")) { return true; } return false; } }
public class LinuxConditional extends AbstractConditional implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { if(super.getOSName(context).toUpperCase().contains("LINUX")) { return true; } return false; } }
只有当当前的操作系统为windows时,才会注入该bean.
测试:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes= {ConditionalConfig.class}) public class ConditionalTest { @Autowired private ApplicationContext context; @Test public void test() { System.out.println(context.getBean(OS.class).getName()); } }
结果返回为window,说明在当前的操作系统中只能创建一个Bean,另外一个Bean的声明并不会执行,否则getBean()方法会出现问题.
原文地址:https://www.cnblogs.com/trekxu/p/9094869.html
时间: 2024-10-08 23:16:55