Spring中如何使用@Value注解实现给Bean属性赋值

目录

  • 属性赋值
  • @Value注解的定义:
  • 测试
    • 1.在添加了Spring依赖的Maven项目中创建
    • 2.在resources目录下创建一个配置文件person.properties
    • 3.创建配置类
    • 4.创建测试类进行测试
    • 5.测试结果:
  • 如何给Bean的属性赋值(注入)
    • 1.通过构造方法设置值。
    • 2.设置注入(通过set方法)

属性赋值 只用Spring注解开发的时候,可以使用@Value搭配@PropertySource注解进行给Bean的属性进行赋值。
@Value

@Value注解的定义:
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Value { /*** The actual value expression: for example {@code #{systemProperties.myProp}}.*/ String value(); }

可以看到@Value注解接受的参数只能是字符串,所以使用时参数都需要带上双引号。并且可以在属性,方法,参数等位置上标注。value属性支持以下三种类型:
基本数据类型,包括String,int,boolean等类型。
SpEL,#{}的形式即表示使用SpEL表达式,一般用于获取环境中其他bean的属性,当使用Elivis运算符“表达式1?:表达式2”,比如#{ “obj.property? :default_value” }形式时,这里的obj是取当前容器中的对象,default_value就是前面的值为空时的默认值。
在主配置类中通过@PropertySource注解加载配置文件,然后通过${ property : default_value}的形式取配置文件中的值,其中default_value表示前面的值为空时的默认值。

测试
1.在添加了Spring依赖的Maven项目中创建
以下两个实体类Student类和Teacher类
public class Teacher { public int id; public String name; public Teacher() {// TODO Auto-generated constructor stubSystem.out.println("teacher-----创建"); } public Teacher(int id, String name) {super(); this.id = id; this.name = name; } //省略getter和setter方法}

在Student类中使用${}取配置文件的值,#{}取容器中的teacher对象的name属性
public class Student{ @Value("1") private int id; @Value("${student.name}") private String name; @Value("${student.address:北京}") private String address; @Value("#{teacher.name?:'老子'}") private String teacherName; @Override public String toString() {return "Student [id=" + id + ", name=" + name + ", address=" + address + ", teacherName=" + teacherName + "]"; }//省略getter和setter方法}


2.在resources目录下创建一个配置文件person.properties
添加以下值:
student.name=张三person.address=广州市


3.创建配置类
使用@PropertySource注解读取外部配置文件person.properties中的key/value保存到运行的环境变量中。
@Configuration@PropertySource("person.properties")public class SpringConfig2 { @Bean public Student student() {return new Student(); }@Bean public Teacher teacher() {return new Teacher(2,"老李"); }}


4.创建测试类进行测试
编写代码获取容器中的id为student的bean和直接获取配置环境的属性值。
public class IoCTest { @Test public void test() {//获取Spring的IOC容器AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig2.class); //从容器中获取beanStudent stu = (Student) applicationContext.getBean("student"); System.out.println(stu); //获取环境变量ConfigurableEnvironment environment = applicationContext.getEnvironment(); String property = environment.getProperty("person.address"); System.out.println(property); //关闭容器applicationContext.close(); }}


5.测试结果:
Spring中如何使用@Value注解实现给Bean属性赋值
文章图片


如何给Bean的属性赋值(注入)
1.通过构造方法设置值。

2.设置注入(通过set方法)
通过property标签(内部是通过调用类的set方法将值注入)
Spring中如何使用@Value注解实现给Bean属性赋值
文章图片

Spring中如何使用@Value注解实现给Bean属性赋值
文章图片

【Spring中如何使用@Value注解实现给Bean属性赋值】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读