springMvc中獲取通過注解獲取properties配置文件(轉)


springMvc的項目中,通過注解@Value獲取properties配置文件中的配置,使用該注解必須引入的包:

spring-beans-4.1.4.RELEASE.jar

下面是需要在spring的配置文件中配置的內容

<?xml version="1.0" encoding="UTF-8"?>
<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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath*:config/autoCreateTable.properties</value>
            </list>
        </property>
    </bean>

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />
    </bean>
</beans>
--------------------- 
作者:孫琛斌 
來源:CSDN 
原文:https://blog.csdn.net/sun5769675/article/details/51789352 
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

然后創建組件,通過注解獲取配置文件的值

 /**
     * 要掃描的model所在的pack
     */
    @Value("#{configProperties['mybatis.model.pack']}") 
    private String pack;

    /**
     * 自動創建模式:update表示更新,create表示刪除原表重新創建
     */
    @Value("#{configProperties['mybatis.table.auto']}")
    private String tableAuto;
--------------------- 
作者:孫琛斌 
來源:CSDN 
原文:https://blog.csdn.net/sun5769675/article/details/51789352 
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

configProperties就是bean的id,[”]中的值就是要取的配置文件中的key,這樣就可以將配置文件中的值映射到代碼中的pack、tableAuto屬性上了。

然后直接注入這個組件就可以了。

原文鏈接:https://blog.csdn.net/sun5769675/article/details/51789352


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM