多环境切换
java配置使用profile
@Profile设置在某个环境下,spring注入对应的bean
public class JavaConfig {
@Bean
@Profile("dev")
DataSource devDs(){
DataSource ds = new DataSource();
ds.setUrl("dev");
ds.setUsername("dev");
return ds;
}
@Bean
@Profile("prod")
DataSource prodDs(){
DataSource ds = new DataSource();
ds.setUrl("prod");
ds.setUsername("prod");
return ds;
}
}
启动环境的时候,不要先传递配置文件,,一旦传入了配置文件,,spring默认就会初始化容器,,但是还没有设置系统的环境,,
public static void main(String[] args) {
// 添加配置类会 初始化容器
// AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
// 设置环境
ctx.getEnvironment().addActiveProfile("prod");
// 设置配置类
ctx.register(JavaConfig.class);
// 初始化容器
ctx.refresh();
DataSource bean = ctx.getBean(DataSource.class);
System.out.println("bean = " + bean);
}
xml使用profile
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<beans profile="dev">
<bean class="com.cj.Dog" id="dog">
<property name="name" value="小黑"/>
</bean>
</beans>
<beans profile="prod">
<bean class="com.cj.Dog" id="dog">
<property name="name" value="小白"/>
</bean>
</beans>
</beans>
@Test
public void test(){
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
ctx.getEnvironment().setActiveProfiles("dev");
ctx.setConfigLocation("profile-beans.xml");
ctx.refresh();
Dog dog = ctx.getBean(Dog.class);
System.out.println("dog = " + dog);
}
@Profile实现
@Profile 本质上是一个条件注解
自定义一个Profile
package com.cj.profile02;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Profiles;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;
import java.util.Arrays;
import java.util.List;
/**
* @author cc
* @date 2024-06-19 20:08
**/
public class MyProfileCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> allAttrs = metadata.getAllAnnotationAttributes(MyProfile.class.getName());
if (allAttrs !=null){
// 拿到value传的值,,,, 传的环境值是个数组
List<Object> value = allAttrs.get("value");
value.forEach(System.out::println);
for (Object val : value) {
// 判断是否是系统环境
boolean b = context.getEnvironment().acceptsProfiles(Profiles.of(((String[]) val)));
if (b){
return true;
}
}
}
return false;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Conditional(MyProfileCondition.class)
public @interface MyProfile {
String[] value();
}