package com.tszr.conditional; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class MyCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return context.getResourceLoader().getResource("classpath:test.properties").exists(); } }
package com.tszr.conditional; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class YourCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return !context.getResourceLoader().getResource("classpath:test.properties").exists(); } }
package com.tszr.dao; public interface MessagePrint { public String showMessage(); }
package com.tszr.service; import com.tszr.dao.MessagePrint; public class MyMessagePrint implements MessagePrint { @Override public String showMessage() { return "test.properties文件存在。"; } }
package com.tszr.service; import com.tszr.dao.MessagePrint; public class YourMessagePrint implements MessagePrint { @Override public String showMessage() { return "test.properties文件不存在!"; } }
package com.tszr.controller; import com.tszr.conditional.MyCondition; import com.tszr.conditional.YourCondition; import com.tszr.dao.MessagePrint; import com.tszr.service.MyMessagePrint; import com.tszr.service.YourMessagePrint; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; @Configuration public class ConditionConfig { @Bean @Conditional(MyCondition.class) public MessagePrint myMessage() { return new MyMessagePrint(); } @Bean @Conditional(YourCondition.class) public MessagePrint yourMessage() { return new YourMessagePrint(); } }
package com.tszr.conditional; import com.tszr.controller.ConditionConfig; import com.tszr.dao.MessagePrint; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class TestMain { private static AnnotationConfigApplicationContext context; public static void main(String[] args) { context = new AnnotationConfigApplicationContext(ConditionConfig.class); MessagePrint mp = context.getBean(MessagePrint.class); System.out.println(mp.showMessage()); } }