第2章:spring中的Bean/2.6 环境参数和占位符/2.6.1 环境参数/2.6.1.1 概念
- 概念与设置
- 指的是为了区分不同的环境而设置的参数,比如开发环境和生产环境
第2章:spring中的Bean/2.6 环境参数和占位符/2.6.1 环境参数/2.6.1.2 参数设置
- 参数设置
- JAVA设置环境变量,比如:System.setProperty("参数名","参数值");比如:
System.setProperty("targetPlatform","dev");
- 从JVM参数中解析,比如:-DParamName = value值
- 注解方式 import org.springframework.context.annotation.Profile;
@Profile("dev")
public Foo devFoo(@Value("${name}") String name) {
Foo foo = new Foo();
foo.setName("dev " + name);
return foo;
}
第2章:spring中的Bean/2.6 环境参数和占位符/2.6.1 环境参数/2.6.1.3 参数激活
- 参数激活
-
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(Ch2Configuration.class);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
//激活某个环境参数
environment.setActiveProfiles("dev");
第2章:spring中的Bean/2.6 环境参数和占位符/2.6.2 占位符2.6.2.1 概念以及格式
- 概念以及格式
- 类似于参数的形式,而这个参数具体的值在另外的地方设置
- 格式:
- 使用注解:
import org.springframework.beans.factory.annotation.Value;
- 声明占位符:
- JAVA中:@Value("${占位符名称}"),比如:
@Value("${name}")
- XML文件中:${占位符名称}
- JAVA中:@Value("${占位符名称}"),比如:
- 使用注解:
第2章:spring中的Bean/2.6 环境参数和占位符/2.6.2 占位符2.6.2.2 占位符赋值
- 占位符赋值
- 声明一个Bean启动占位符解析
//启动占位符工作机制
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
- 为占位符赋值
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(Ch2Configuration.class);
//获取环境对象
ConfigurableEnvironment environment = applicationContext.getEnvironment();
//激活某个环境参数
environment.setActiveProfiles("dev");
//给占位符赋值
MutablePropertySources propertySources = environment.getPropertySources();
//name为占位符名称,"my foo"为占位符的值
propertySources.addLast(new MapPropertySource("mapSource", Collections.singletonMap("name", (Object)"my foo")));
第2章:spring中的Bean/2.6 环境参数和占位符/2.6.3 实例(已经编译通过)
- 实例(已经编译通过)