在此之前,我们已经了解到了spring容器中bean的整个生命周期,既然bean已经创建成功,但是我们该如何在bean创建时给各个属性赋值呢?这是本篇文章将要学习的内容。
1.xml方式进行属性赋值
<bean id="student" class="com.xinhua.study.bean.Student">
<property name="id" value="1"/>
<property name="name" value="xiaoming"/>
</bean>
直接通过property标签赋值即可.
2.@Value进行属性赋值
- 修改com.xinhua.study.bean下的Student类,在id和name上分别通过@Value注解赋值
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Student {
@Value("1")
private Integer id;
@Value("xiaoming")
private String name;
}
- 在com.xinhua.study.config包下创建AnnotationConfigOfPropertiesSet配置类:
@Configuration
public class AnnotationConfigOfPropertiesSet {
@Bean
public Student student() {
return new Student();
}
}
- 在src/test/java的com.xinhua.study.test包下创建AnnotationConfigTestOfPropertiesSet 测试类,并添加测试方法
@Slf4j
public class AnnotationConfigTestOfPropertiesSet {
@Test
public void testValue() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AnnotationConfigOfPropertiesSet
.class);
Student bean = applicationContext.getBean(Student.class);
log.info("bean信息:{}",bean);
}
}
- 执行测试方法,测试结果:
可见,@Value注解赋值成功。
@value常见用法
- 基本数值,数字、字符串、布尔类型常量值都可以,如上面的用法@Value(“1”)及@Value(“xiaoming”)
- SpEL表达式:@Value("#{表达式}")
- ${}取出配置文件即运行环境中的值:@Value("${变量名}")
测试以上三种用法:
- 修改Student类
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Student {
//测试SpEl表达式
@Value("#{2-1}")
private Integer id;
@Value("xiaoming")
private String name;
//测试从配置文件读取
@Value("${age}")
private Integer age;
//防止之前的代码报错
public Student(Integer id, String name) {
this.id = id;
this.name = name;
}
}
- 在src/main/resources下创建student.properties并添加键值对age = 18
- 修改AnnotationConfigOfPropertiesSet配置类,添加@PropertySource(“student.properties”)
- 执行AnnotationConfigTestOfPropertiesSet 测试类中的测试方法:
@Value注解的三种使用方式都测试通过。
3.@PropertySource导入配置文件
在刚刚测试@Value的第三种用法@Value("${变量名}")时,我们在配置类AnnotationConfigOfPropertiesSet上添加了@PropertySource(“student.properties”)注解,用于将外部的配置文件student.properties文件导入,保存到spring的运行环境变量中,对应于xml配置方式:
<context:property-placeholder location="classpath:student.properties"/>
在程序中可以通过spring容器获取环境信息并获取导入的配置文件中的键值对数据,修改AnnotationConfigTestOfPropertiesSet 测试类的测试方法:
@Slf4j
public class AnnotationConfigTestOfPropertiesSet {
@Test
public void testValue() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AnnotationConfigOfPropertiesSet
.class);
Student bean = applicationContext.getBean(Student.class);
log.info("bean信息:{}",bean);
String age = applicationContext.getEnvironment().getProperty("age");
log.info("配置文件中的age:{}",age);
}
}
运行后,可以打印出来配置文件中的age的数据信息。
关于spring属性赋值相关的注解学习到此结束~~