有關在xml的bean的property在java中的注入

問題:首先由一個FileUpLoadController,在該類中用Autowired註解注入FileUpUtils。 而類FileUpUtils須要一些配置參數,好比文件服務器接口的路徑和方法名,而這些參數,咱們想要配置在properties文件中。 解決: 1.在properties中配置參數spring

#文件服務器
file.upload.url=http://100.10.0.10/fs-api/
upload.file.method=uploadFile.hc
download.file.method=downloadFile.hc
search.file.method=searchFile.hc
remove.file.method=removeFile.hc

2.在xml中讀取properties中的屬性,並賦值到FileUpUtils的bean的property屬性中。api

<!-- 引入配置文件 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:data-access.properties" />
	</bean>
	<!-- 文件服務器工具類,由於上面已經讀取properties文件,因此下面就能夠直接取值 -->
	<bean id="fileUploadUtils" class="com.contract.service.utils.FileUploadUtils">
		<property name="fileUploadUrl" value="${file.upload.url}"></property>
		<property name="uploadFile" value="${upload.file.method}"></property>
		<property name="downloadFile" value="${download.file.method}"></property>
		<property name="searchFile" value="${search.file.method}"></property>
		<property name="removeFile" value="${remove.file.method}"></property>
	</bean>

3.在FileUpUtils中直接用Autowired註解,獲取fileUploadUrl,uploadFile等參數。 可是這種方法在項目啓動的時候報錯。這是由於在掃描組件的時候,初始化FileUploadController時候,要初始化FileUpUtils,可是這個時候,FileUpUtils中的fileUploadUrl等參數,尚未被初始化,獲取不到所以,沒有值。這個時候程序啓動的時候被報錯。由於Autowired屬性默認的是required=true,也就是該參數是必須的,所以報錯,這個時候咱們在@Autowired註解後面加一個required=false。也就是@Autowired(required=false) 這樣就能夠了,並且程序啓動後進行程序操做的時候,FileUpUtils已經初始化成功,而且參數注入,也就是能夠正常的進行使用了。服務器

相關文章
相關標籤/搜索