1. 程式人生 > 實用技巧 >Spring註解之@PropertySource&@Value

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