通过@Value读取属性的值
新建maven,pom如下
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
新建bean
public class Bird {
@Value("张三")
private String name;
@Value("#{23-1}")
private Integer age;
@Value("${bird.color}")
private String color;
public Bird() {
}
public Bird(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Bird{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
'}';
}
}
在resources新建test.perperties
bird.color=red
新建config配置类,并加载属性文件
@Configuration
@PropertySource(value = {"classpath:/test.properties"})
public class DemoConfig {
@Bean
public Bird bird() {
return new Bird();
}
}
新建启动类
public class DemoApp {
public static void main(String[] args){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(DemoConfig.class);
System.out.println("IOC容器初始化完成");
String[] names = app.getBeanDefinitionNames();
for (int i = 0; i < names.length; i++) {
String name = names[i];
System.out.println(name);
}
Bird bean = (Bird)app.getBean("bird");
System.out.println(bean);
//属性信息是保存在运行环境变量里面
ConfigurableEnvironment environment = app.getEnvironment();
String color = environment.getProperty("bird.color");
System.out.println("environment:"+color);
app.close();
}
}
输出结果:
IOC容器初始化完成
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
demoConfig
bird
Bird{name='张三', age=22, color='red'}
red