1. 程式人生 > >SpringMVC 使用 @Value獲取properties檔案中的屬性值

SpringMVC 使用 @Value獲取properties檔案中的屬性值



我的專案目錄結構

test
----- java
--------- com.test
---------------Proporties.java
---------------Test.java
-----resource
--------- applicationContext.xml
--------- application.properties

-------------------------------------------------------------------

application.properties內容

jdbc.code = "this is a code"

-------------------------------------------------------------------
Proporties.java 原始碼

package com.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Proporties {

	@Value("#{configProperties['jdbc.code']}")
	private String code;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	
}

-------------------------------------------------------------------

applicationContext.xml 配置

<!-- 獲取properties中的值 -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
	<value>classpath:application.properties</value>
    </list>
  </property>
</bean>
	
<!-- Spring的動態變數,能在bean中直接呼叫 --> 
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="properties" ref="configProperties" />
</bean>

<!-- 使用Annotation自動註冊Bean ,掃描 Component-->
<context:component-scan base-package="com.test" use-default-filters="false"><!-- base-package 如果多個,用“,”分隔 -->
	<context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
</context:component-scan>
-------------------------------------------------------------------

Test.java 原始碼

@ContextConfiguration(locations = { "classpath:applicationContext.xml" })  
@RunWith(SpringJUnit4ClassRunner.class
public class Test{

	
    @Antowird
    private Proporties proporties;

    @Test
    public void testProperties(){
    
    System.out.println("獲取的值為:" + proporties.getCode());
    }
}