文章目录
Spring根据环境获取bean对象
开发中,我们需要根据的程序环境,动态的获得到相应的bean对象。整个流程没有配置文件的参与
- 自定义一个接口,将需要创建的类实现一个接口
- 创建多个实现
Condition
接口的类(一个该类型的类,代表一种环境) - 自定义一个类,判断当前的是什么环境
举例
自定义一个接口,将需要创建的类实现该接口
ShowService
接口
public interface ShowService {
public void show();
}
ShowService
接口的实现类 LinuxShowServiceImpl
public class LinuxShowServiceImpl implements ShowService {
@Override
public void show() {
System.out.println("linux --- ls");
}
}
ShowService
接口的实现类 WindowsShowServiceImpl
public class WindowsShowServiceImpl implements ShowService {
@Override
public void show() {
System.out.println("windows ...dir");
}
}
创建多个实现 Condition
接口的类(一个该类型的类,代表一种环境)
如果环境中存在字符串 linux
返回true
package com.bb.condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class LinuxShowCondition implements Condition {
@Override
public boolean matches(ConditionContext context
, AnnotatedTypeMetadata metadata) {
String[] profiles = context.getEnvironment().getActiveProfiles();
for (String p : profiles) {
if(p.contains("linux")){
return true;
}
}
System.out.println("-----windows------");
return false;
}
}
如果环境中存在字符串 window
返回true
package com.bb.condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class WindowsShowCondition implements Condition {
@Override
public boolean matches(ConditionContext context
, AnnotatedTypeMetadata metadata) {
String[] profiles = context.getEnvironment().getActiveProfiles();
for (String p : profiles) {
if(p.contains("window")){
return true;
}
}
System.out.println("--linux---");
return false;
}
}
创建一个实现 Condition
接口的类
根据不同的环境返回不同bean对象(特定类/方法注解,实现特定接口类组合实现)
@Configuration
public class JavaConfig {
@Bean
@Conditional(WindowsShowCondition.class)
public WindowsShowServiceImpl getWindowsObject(){
return new WindowsShowServiceImpl();
}
@Bean
@Conditional(LinuxShowCondition.class)
public LinuxShowServiceImpl getLinuxObject(){
return new LinuxShowServiceImpl();
}
}
测试
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
ac.getEnvironment().setActiveProfiles("windows");
ac.register(JavaConfig.class);
ac.refresh();
ShowService bean = ac.getBean(ShowService.class);
bean.show();
}
}
打印结果
-----windows------
windows ...dir
执行流程
- 在环境中设置字符串
windows
- 将可选环境和对应的bean对象进行登记
- 根据接口类型来获得bean对象
- 分析有环境对象,循环解析
JavaConfig
中方法的注解,判断是否执行该方法,以符合该对象。
总结:这种方式实现环境与bean对象类型的绑定的方式比较新奇。
项目打包 提取码:f8zi
环境:eclipse
导入jar包 (可能有些包没有使用)
com.springsource.org.apache.commons.logging-1.1.1.jar
spring-aop-4.3.10.RELEASE.jar
spring-aspects-4.3.10.RELEASE.jar
spring-beans-4.3.10.RELEASE.jar
spring-context-4.3.10.RELEASE.jar
spring-core-4.3.10.RELEASE.jar
spring-expression-4.3.10.RELEASE.jar