当前位置 博文首页 > blackball1998的博客:Bean属性赋值
当我们给Bean中的属性赋值时,除了常规的赋初始值,还可以通过@Value
注解赋值
@Component
public class Person {
@Value("18")
private int age;
@Value("wang")
private String name;
}
那么这种做法和常规赋值的做法相比有什么优势呢?通过@Value
赋值,可以进行数学计算,更常用的是,这种方式可以从配置文件中读取值
在设置@Value
注解的属性时,可以使用#{}
,括号中填入数学运算公式的方式来赋值,Spring在给属性赋值的时候会先进行数学计算得到值再填充属性
@Component
public class Person {
@Value("#{20-2}")
private int age;//age=18
@Value("wang")
private String name;
}
在设置@Value
注解的属性时,可以使用${}
,括号中填入项目中配置文件的值,Spring在给属性赋值的时候会先从配置文件中读取值再填充属性
我们先在Spring Boot项目中的application.properties文件中设置一个值
person.name=wang
然后在@Value
注解的属性中通过配置文件获取值
public class Person {
@Value("#{20-2}")
private int age;
@Value("${person.name}")
private String name;//name="wang"
}
@Value
注解也可以添加在方法的形参上,这种方法多用于使用@Bean
注解向IOC容器中添加Bean的时候
@Configuration
public class MyConfiguration {
@Bean
public Person person(@Value("${person.age}") int age, @Value("${person.name}") String name) {
return new Person(age, name);
}
}
之前我们在Spring Boot项目自带的application.properties文件设置了属性的值,由于application.properties会被Spring Boot自动识别,所以这没问题。现在我们重新创建一个properties文件来设置属性的值,这时候就需要用到@PropertySource
注解了
#配置在person.properties中
person.name=wang
现在我将属性的值写在person.properties中,这样是无法被Spring读取的,这时候需要在Bean的类上添加@PropertySource
注解,绑定配置文件的路径,这样就可以获取到对应配置文件中的值了
@Component
@PropertySource("classpath:person.properties")
public class Person {
@Value("#{20-2}")
private int age;
@Value("${person.name}")
private String name;
}
如果需要绑定多个配置文件,可以使用@PropertySources
注解
有时候我们为一个Bean赋值时,需要用到IOC容器中的其他Bean,这时候我们可以在构造Bean的时候也是用@Autowired
注解来自动获取容器中的Bean
我们来创建以下Demo,Person类中包含一个Car类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private int age;
private String name;
private Car car;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Car {
private String brand;
private String color;
}
将一个Person对象和一个Car对象分别添加到IOC容器中,在构造Person的Bean时,方法传入一个Car对象,并标注@Autowired
注解,此时Spring将会在IoC容器中寻找Car的Bean,并用于构造Person的Bean
@Configuration
public class MyConfiguration {
@Bean
public Person person(@Autowired Car car) {
return new Person(18, "wang", car);
}
@Bean
public Car car() {
return new Car("Ferrari", "red");
}
}
测试是否自动注入了Car的Bean
@SpringBootTest
class DemoApplicationTests {
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
测试结果如下
顺利从容器中获取Car的Bean并注入到Person的Bean中
一般地,容器中同类型的Bean只会有一个,这时候可以省略@Autowired
,而在开发中我们一般也省略
@Configuration
public class MyConfiguration {
@Bean
public Person person(Car car) {
return new Person(18, "wang", car);
}
@Bean
public Car car() {
return new Car("Ferrari", "red");
}
}
如果使用@Component
的方式添加Bean,可以将@Autowired
添加在有参构造器之上