新建 maven 项目,引入spring 依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
@Value赋值
新建一个实体类
public class Employee {
private String name;
private Integer age;
private String job;
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;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", job='" + job + '\'' +
'}';
}
}
配置类
@Configuration
public class AttributeAssignmentConfig {
@Bean
public Employee getEmployee() {
return new Employee();
}
}
测试:
public class AttributeAssignmentTest {
@Test
public void testValueAnnotation() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AttributeAssignmentConfig.class);
Employee employee = context.getBean(Employee.class);
System.out.println(employee);
}
}
结果:这时属性值都是空
Employee{name='null', age=null, job='null'}
在 Employee 类上添加 @Value
@Value("Tom")
private String name;
@Value("#{20+5}") // Spring spel #{}
private Integer age;
测试结果:
Employee{name='Tom', age=25, job='null'}
@PropertySource 加载外部配置文件
为防止配置文件中的中文打印乱码,请提前配置utf-8编码
创建配置文件:emp.properties
emp.job=Java开发
配置类上加上配置文件
//使用@PropertySource读取外部配置文件中的k/v保存到运行的环境变量中;加载完外部的配置文件以后使用${}取出配置文件的值
@PropertySource("classpath:/emp.properties")
@Configuration
public class AttributeAssignmentConfig {
Employee 类上 添加 @Value("${emp.job}")
@Value("${emp.job}")
private String job;
测试:
Employee{name='Tom', age=25, job='Java开发'}