(一)IOC 容器:【9】@Value 给属性赋值

一、配置文件的赋值

  调用无参构造器给容器中注册一个 Bean 组件:

@Configuration
public class MainConfigOfPropertyValues {

    @Bean(name = "person")
    public Person person01() {
        return new Person();
    }
}

  调用Person的无参构造器,然后创建对象,这时对象的属性都是没有值的,为 null。

  之前在配置文件中,可以使用 value 来给属性赋值:

二、使用 @Value 注解给JavaBean的属性赋值

  可以在属性上面使用 @Value 注解来给属性赋值。
  支持三种方式:
1、基本数据类型
2、可以使用 SpEL 表达式,#{},如#{18-2}
3、可以使用${},读取配置文件【properties】中的值(在运行环境变量里面的值)

  

  在 Person 类中使用 @Value 注解来给属性赋值:

public class Person {

    @Value("张三")
    private String name;

    @Value("#{20 - 2}")
    private Integer age;

    @Value("${person.nickName}")
    private String nickName;
}

  创建一个外部的配置文件 person.properties

person.nickName=小张三
 
 
  在配置类上面使用 @PropertySource 导入properties文件
//使用@PropertySource读取外部配置文件中K/V保存到运行的环境变量中;
//加载完外部的配置文件之后使用 ${} 取出配置文件中的值。
@PropertySource(value = {"classpath:/person.properties"})   //读取配置文件的值,可以写多个
@Configuration
public class MainConfigOfPropertyValues {

    @Bean(name = "person")
    public Person person01() {
        return new Person();
    }
}

  注意:@PropertySource 是一个可重复注解,可以使用多个 @PropertySource或者直接使用 @PropertySources;

  

  测试:

    @Test
    public void test01() {
        AnnotationConfigApplicationContext ioc = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);

        System.out.println("IOC容器创建完成");

        String[] names = ioc.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        Person person = (Person) ioc.getBean("person");
        System.out.println("person = " + person);

        Environment environment =  ioc.getEnvironment();
        //获取配置文件中的值
        String property =  environment.getProperty("person.nickName");
        System.out.println(property);

        ioc.close();

    }

  可以发现,声明在 properties 文件中的值会添加到环境变量中,可以直接从运行环境中获取配置变量的值。

 

原文地址:https://www.cnblogs.com/niujifei/p/15550268.html