spring @condition注解是用来在不同条件下注入不同实现的
demo如下:
package com.foreveross.service.weixin.test.condition; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; /** * * windows下的环境 * */ public class WindowsCondition implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Windows"); } }
package com.foreveross.service.weixin.test.condition; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class LinuxCondition implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getEnvironment().getProperty("os.name").contains("Linux"); } }
package com.foreveross.service.weixin.test.condition; public interface ListService { String showListCmd(); }
package com.foreveross.service.weixin.test.condition; import org.springframework.stereotype.Service; @Service public class LinuxService implements ListService { public String showListCmd(){ return "ls"; } }
package com.foreveross.service.weixin.test.condition; import org.springframework.stereotype.Service; @Service public class WindowsService implements ListService{ public String showListCmd(){ return "dir"; } }
package com.foreveross.service.weixin.test.condition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration public class MyConfiguration { @Bean(name = "service") @Conditional(WindowsCondition.class) public ListService windowsService() { return new WindowsService(); } @Bean(name = "service") @Conditional(LinuxCondition.class) public ListService linuxEmailerService() { return new LinuxService(); } }
package com.foreveross.service.weixin.test.condition; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(MyConfiguration.class); ListService service= context.getBean(ListService.class); System.out.println("操作符为:"+service.showListCmd()+",系统为:"+context.getEnvironment().getProperty("os.name")); context.close(); } }