标签:sys ica framework work new inter 开发框架 nal div
演示在windows和linux系统下,初始化不同的bean,windows和linux作为判断条件;
条件的构造需要类实现Condition接口,并实现matches方法
package com.wisely.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");
}
}
package com.wisely.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");
}
}
package com.wisely.conditional;
public interface CommandService {
public String showListCommand();
}
package com.wisely.conditional;
public class WindowsCommnadService implements CommandService {
public String showListCommand() {
return "dir";
}
}
package com.wisely.conditional;
public class LinuxCommandService implements CommandService {
public String showListCommand() {
return "ls";
}
}
package com.wisely.conditional;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DemoConfig {
@Bean
@Conditional(WindowsCondition.class)
public CommandService commandService() {
return new WindowsCommnadService();
}
@Bean
@Conditional(LinuxCondition.class)
public CommandService linuxEmailerService() {
return new LinuxCommandService();
}
}
package com.wisely.conditional;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext("com.wisely.conditional");
CommandService cs = context.getBean(CommandService.class);
System.out.println(cs.showListCommand());
context.close();
}
}
输出结果
dir
package com.wisely.conditional;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
System.setProperty("os.name", "Linux");
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.wisely.conditional");
CommandService cs = context.getBean(CommandService.class);
System.out.println(cs.showListCommand());
context.close();
}
}
输出结果
标签:sys ica framework work new inter 开发框架 nal div
原文地址:https://www.cnblogs.com/Jeely/p/11949999.html