上一節,我們學習了如何使用Resource注,這節我們一起來看下@Value注解的使用。話不多說,直接上幹貨。
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIjBXPt9mcm9jMzUWO5cjZhNGO4IjZklDO2gDN0QmM1gDMiJTMiRDMz8CXwsWO0EHbyomdx1Sat42YtM3b09CXul2ZpJ3bvwVbvNmLn1WavFWa0V3b05iNyA3Lc9CX6MHc0RHaiojIsJye.jpg)
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 @Resource注解的使用場景詳解
下一節:Spring注釋類元件講解,敬請關注……