Spring 注解之 @PropertySource @Value

@Value注解和@PropertySource注解配合使用可以将(*.properties)配置文件中的内容动态的注入到实体类中.具体步骤如下:

  1、自定义实体类(Person.java)

// 对象注入Spring容器中,交由Spring进行管理
@Component
// 加载classpath下的application01.properties配置文件中的信息
@PropertySource("classpath:/application01.properties")
// 实体类省略了set/get和toString方法
public class Person {
    @Value("${id}")
    private String id;
    @Value("${person.name}")
    private String name;
    @Value("${person.xiaomaomao.age}")
    private String age;
}

  2、配置文件内容(application01.xml,配置文件放置在resources下)

id=9527
person.name=xiaomaomao
person.xiaomaomao.age=22

  3、配置类

@Configuration
@ComponentScan("com.spring01")
public class SpringConfiguration {
}

  4、测试类

public class SpringDemo {

    @Test
    public void springTest01() throws Exception {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        Person person = context.getBean("person", Person.class);
        System.out.println(person);

        // properties中的配置文件内容会被加载到Spring的环境中,可以通过Environment对象获取
        Environment environment = context.getEnvironment();
        String id = environment.getProperty("id");
        String name = environment.getProperty("person.name");
        String age = environment.getProperty("person.xiaomaomao.age");
        System.out.println(id + "   " + name + "   " + age);

    }
}

  5、测试结果

Person{id=9527, name='xiaomaomao', age=22}
9527   xiaomaomao   22

  

原文地址:https://www.cnblogs.com/xiaomaomao/p/13561371.html