天天看點

Spring @Value注解的經典用法

作者:小林的美好生活

上一節,我們學習了如何使用Resource注,這節我們一起來看下@Value注解的使用。話不多說,直接上幹貨。

Spring @Value注解的經典用法
@Value通常用于注入外部化屬性,即外部配置屬性的注入,首先我們建立一個屬性檔案config.properties,内容如下圖,其次定義一個Person類,包含一個name屬性,我們使用Value注解來對它的值進行注入。spring項目啟動類及xml配置如代碼塊示例,如下:
Spring @Value注解的經典用法

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Person {

    @Value("${author.name}")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <context:component-scan base-package="model"/>
    <context:property-placeholder location="classpath:config.properties"/>
</beans>

public class StartUp {
    public static void main(String[] args) {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        Person person = (Person) applicationContext.getBean("person");
        System.out.println(person.toString());
    }
}           

經過執行後,結果顯示如下:

Spring @Value注解的經典用法

我們可以看到配置在屬性檔案中的屬性值成功注入到了執行個體化的對象當中,即注入成功。

Spring @Value注解的經典用法

以上即是本節的所有内容,如有錯誤之處,歡迎留言指正,同時歡迎感興趣的同學關注作者,後面會不斷分享。

上一節:Spring @Resource注解的使用場景詳解

下一節:Spring注釋類元件講解,敬請關注……