springmvc通過@Value註解讀取Properties配置檔案的值,junit測試可以取到值,但是在業務中無法讀取
最近試著做了個springmvc 專案,在加入 發郵件 功能時遇到的問題。
Spring 通過註解獲取*.porperties檔案的內容,除了xml配置外,還可以通過@value方式來獲取。
@value是需要spring註解掃描的,所以要將spring註解掃描配置中加上實體類的包名路徑,實體類中也應新增@Component
spring配置檔案部分程式碼如下@Component public class MailBean { //實體類前加@Component ,讓spring掃描到該實體類,預設是單例模式,該實體類的功能是從 data.properties 資原始檔中讀取對應的內容 @Value("#{configProperties['emailhost']}") private String emailHost; @Value("#{configProperties['emailform']}") private String emailFrom; @Value("#{configProperties['emailname']}") private String emailUsername; @Value("#{configProperties['emailpassword']}") private String emailPassword; public String getEmailHost() { return emailHost; } public String getEmailFrom() { return emailFrom; } public String getEmailUsername() { return emailUsername; } public String getEmailPassword() { return emailPassword; }
資原始檔內容為<!-- 自動掃描bugkiller包 ,將帶有註解的類 納入spring容器管理 --> <context:component-scan base-package="com.myweb"></context:component-scan> <!-- 引入配置檔案 --> <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath:data.properties</value> <value>classpath:application.properties</value> </list> </property> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configProperties" /> </bean>
emailhost=郵箱的閘道器
emailname=你的使用者名稱
emailpassword=你的密碼
emailform=發件郵箱 //具體值需根據自身情況配置
這樣配置完了,從junit測試中可以正常取到 properties中配置的值
@Test public void test(){ ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); MailBean connInfo = appContext.getBean(MailBean.class); System.out.println(connInfo.getEmailHost()); System.out.println(connInfo.getEmailFrom());
<span style="white-space:pre"> </span>//可以正常獲取<span style="white-space:pre"> </span>
System.out.println(connInfo.getEmailUsername());
}
但一在具體業務中使用的時候get到的是null
後來發現原來我在業務中還是用的 new來建立的實體類 Mailbean ,但Mailbean 已經通過@Component 加入了Spring的管理中了,並且預設的單例,直接new肯定是不對的 ,所以在業務中通過 @Resourceprivate MailBean mailBean; 注入進來,當然該業務類之前也要加註釋交給spring管理, 這樣就能成功的取到值了,在junit測試時是通過
MailBean connInfo = appContext.getBean(MailBean.class);
獲取的bean,所以能正常取值,在業務中的話記得要通過@resource 注入進來,不然是獲取不到該bean的奧,
另外在修改spring 配置檔案時,新增如下程式碼時會丟擲一些警告,說是沒有許可權建立某些檔案
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:data.properties</value>
<value>classpath:application.properties</value>
</list>
</property>
</bean>
警告 : Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKey 等等。。。
應該實在寫入登錄檔是許可權不夠引起的 ,只需在命令視窗開啟 regedit登錄檔管理,在HKEY_LOCAL_MACHINE\Software\JavaSoft\ 下建立 Prefs項即可