1. 程式人生 > >spring @Value 注入配置檔案內容

spring @Value 注入配置檔案內容

</pre>1,在spring配置檔案裡引入util的名稱空間<p></p><p></p><pre name="code" class="html"><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    <span style="white-space:pre">	</span>xmlns:util="http://www.springframework.org/schema/util"</span> xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"
	default-lazy-init="true">
2,掃描註解元件 @Component,@Service,讓bean處在spring的管理下,因為只有在spring管理下的bean,才能使用@Value的方式從配置檔案裡取值
<!-- 使用Annotation自動註冊Bean,解決事物失效問題:在主容器中不掃描@Controller註解,在SpringMvc中只掃描@Controller註解。  -->
	<context:component-scan base-package="com.money"><!-- base-package 如果多個,用“,”分隔 -->
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
</pre><pre name="code" class="html">3,載入配置檔案
</pre><pre name="code" class="html"><!-- 載入應用屬性例項,可通過  @Value("#{APP_PROP['jdbc.driver']}") String jdbcDriver 方式引用 -->
<util:properties id="APP_PROP" location="classpath:resources/money.properties" local-override="true"/>
如果要載入多個配置檔案,再定義一個就行
<util:properties id="APP_PROP2" location="classpath:resources/money.properties" local-override="true"/>
4,bean裡使用,普通java類使用 @Component註解,service 使用,@Service註解,controller使用 @Controller註解
@Component
public class Test {
	//如果是隻載入了一個配置檔案,可以直接這樣寫,通過 $ 獲取
	@Value("${resourceUrl.path}")
	private String tt;
	
	//也可以根據xml裡配置的id,指定配置檔案,通過 # 獲取
	@Value("#{APP_PROP['resourceUrl.path']}")
	private String tt1;
	
	@Value("#{APP_PROP2['resourceUrl.path']}")
	private String tt2;
	
	public String getTt(){
		return tt;
	}
	public String getTt1(){
		return tt1;
	}
	public String getTt2(){
		return tt2;
	}
}


5,需要注意的是,使用@Value注入後,可以在該類裡直接使用,如果要被其他類呼叫,則在其他類裡也需通過注入的方式引用該類</span>
@Autowired
Test test;
只能通過注入的物件呼叫,如果是通過 new的方式建立的test物件,呼叫 test.getTt()時返回null


</pre><br /><br /><pre>