我先简单的说一下为什么我要将这两个知识点放一起:因为他们都涉及到了jvm参数问题。
一、条件注解的实现方法@Conditional
如下的IOC容器:由于@Bean注解后没有加东西,所以下面的两个bean的id都为car,究竟得到哪个bean就取决于@Conditional注解括号里的东西!
@Configuration
public class MyConfig {
@Bean
@Conditional(OilCarCondition.class)
public Car oilCar(){
return new OilCar();
}
@Bean
@Conditional(EnergyCarCondition.class)//条件注解 使用时需在run edit_configuration 中配置vm参数
public Car EnergyCar(){
return new EnergyCar();
}
}
下面编写OilCarCondition.class和EnergyCarCondition.class
package condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class OilCarCondition implements Condition {
//如果当前环境是 oil ,则加入OilCar
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
//获取环境
Environment environment = conditionContext.getEnvironment();
String carType = environment.getProperty("car.type");
if(carType.contains("oil"))
return true;
return false;
}
}
package condition;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
public class EnergyCarCondition implements Condition {
//如果当前环境是 energy ,则加入energyCar
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
//获取环境
Environment environment = conditionContext.getEnvironment();
String carType = environment.getProperty("car.type");
if(carType.contains("energy"))
return true;
return false;
}
}
接下来需要指定jvm参数:
-Dcar.type=energy 能源车
-Dcar.type=oil 煤油车
二、环境切换问题@Profile
IOC容器如下:
@Configuration
public class MyConfig {
@Profile("myApple")
@Bean("apple")
public Fruit apple(){
return new Apple();
}
@Profile("myBanana")
@Bean("banana")
public Fruit banana(){
return new Banana();
}
}
提前编写的Apple类和Banana
package entity;
public class Apple extends Fruit{
}
package entity;
public class Banana extends Fruit{
}
如果直接从容器中获取id为apple和id为banana的两个bean是获取不到的
只有设置jvm参数指定环境才能生效:-Dspring.profiles.active=@Profile环境名
容器中才能被获取!
还可以通过硬编码方式制定环境
注意:第一行代码后面的new AnnotationConfigApplicationContext();括号中不需要指定任何参数。
public static void textAnnotation(){
ApplicationContext context = new AnnotationConfigApplicationContext();
ConfigurableEnvironment environment = (ConfigurableEnvironment)context.getEnvironment();
//设置环境
environment.setActiveProfiles("myBanana");
//保存点
((AnnotationConfigApplicationContext) context).register(MyConfig.class);
((AnnotationConfigApplicationContext) context).refresh();
Object banana = context.getBean("banana");
// Object apple = context.getBean("apple");
System.out.println(banana);
}