溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Spring的@Value屬性怎么賦值

發(fā)布時間:2022-03-22 10:25:57 來源:億速云 閱讀:288 作者:iii 欄目:云計算

本篇內(nèi)容主要講解“Spring的@Value屬性怎么賦值”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Spring的@Value屬性怎么賦值”吧!

1.建立新的配置類

建立新的配置類,  @Configuration指定為配置類 ,@Bean加載Person類,為測試做準備,代碼如下:
@Configurationpublic class MainConfigOfPropertyValues {      @Bean   public Person person(){      return new Person();   }
}

2.建立新的測試方法

建立測試方法,獲取并打印Person 的Bean  
public class IOCTest_PropertyValue {   AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);   @Test   public void test01(){      printBeans(applicationContext);      System.out.println("=============");            Person person = (Person) applicationContext.getBean("person");      System.out.println(person);         }      private void printBeans(AnnotationConfigApplicationContext applicationContext){      String[] definitionNames = applicationContext.getBeanDefinitionNames();      for (String name : definitionNames) {         System.out.println(name);      }   }
}
測試類運行結果如下,可以看到默認情況下person 這個Bean 所有的字段都為空。下面將進行賦值  

Spring的@Value屬性怎么賦值

3.通過@Value 進行賦值

在xml配置文件可以通過bean 標簽中包含  property進行屬性賦值
<bean id="person" class="com.atguigu.bean.Person"  scope="prototype" >    <property name="age" value="18"></property>    <property name="name" value="zhangsan"></property>  </bean>
在注解開發(fā)中可以使用@Value  對屬性進行賦值。
其中可以賦值
1.基本數(shù)據(jù)類型
@Value("張三")private String name;
2.可以寫SpEL;#{} ,即sping 的表達式
@Value("#{20-2}")private Integer age;
3.可以寫${};取出配置文件【properties】中的值(在運行環(huán)境變量里面的值)  
@Value("${person.nickName}")private String nickName;
運行結果如下,成功賦值  

Spring的@Value屬性怎么賦值


4.通過@PropertySource  加載配置文件,并進行注入

在xml 配置文件時,可以通過  context  :property-placeholder標簽,引入配置文件。
<context:property-placeholder location="classpath:person.properties"/>
1.在注解開發(fā)中,可使用  @PropertySource 加載外部配置文件
@PropertySource(value={"classpath:/person.properties"})
2.創(chuàng)建屬性文件  person.properties   
person.nickName=小李四
即可通過@Value + ${}獲取到配置的文件的值,或使用容器的  getEnvironment()方法進行調(diào)用  getProperty(  "person.nickName"  );獲取配置文件中的內(nèi)容。
ConfigurableEnvironment environment = applicationContext.getEnvironment();String property = environment.getProperty("person.nickName");System.out.println(property);
添加測試運行結果如下:  

Spring的@Value屬性怎么賦值

5.拓展@Value  、@PropertySource 

@Value 靜態(tài)變量賦值

在處理靜態(tài)變量時候,使用上面的@Value的用法是無法獲取到配置文件中的數(shù)據(jù)的,只能獲取到null,所以要進行如下更改。

@PropertySource注解的地址可以是以下兩種:

 classpath路徑:"classpath:/com/myco/app.properties"

 文件對應路徑:"file:/path/to/file"

到此,相信大家對“Spring的@Value屬性怎么賦值”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI