1. 程式人生 > >Java程式碼中獲取配置檔案(config.properties)中內容的兩種方法

Java程式碼中獲取配置檔案(config.properties)中內容的兩種方法

方法千千萬,本人暫時只總結了兩種方法。

(1)

config.properties中的內容如圖

在applicationContext.xml中配置

<!-- 引入配置檔案 -->  
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
	    <property name="locations">
			<list>
			  <value>classpath:config.properties</value>
			</list>
		</property>
	</bean>
在Controller層中使用springMVC的@Value註解獲得配置檔案的內容:
    @Value("#{configProperties['local']}")
    private String localAddress;
在程式碼中寫localAddress即可得到配置檔案中local的值。

(2)

在applicationContext.xml中配置

<!-- 引入配置檔案 -->  
    <bean id="configPropertyConfigurer"  
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        <property name="order" value="2" />  
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="locations">
			<list> 
				<value>classpath:config.properties</value>
			</list>
		</property>  
    </bean>  
  
    <!--配置全域性變數-->
    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="singleton" value="true"/>
        <property name="properties">
              <props>
              		<prop key="csdn.url">${csdn.url}</prop>
              </props>
        </property>
    </bean>
在需要用到的類中注入Properties,注意引數必須和配置全域性變數的id相同
   @Autowired
   protected Properties properties;
然後在類中可以通過properties.getProperty("csdn.url")獲取配置檔案中csdn.url的內容

當然,兩種獲取引數的方法也可以同時使用,需要在applicationContext.xml中配置

<!-- 引入配置檔案 -->  
    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
	    <property name="locations">
			<list>
			  <value>classpath:config.properties</value>
			</list>
		</property>
	</bean>
	
	<bean id="configPropertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
		<property name="order" value="2" />  
        <property name="ignoreUnresolvablePlaceholders" value="true" />
		<property name="properties" ref="configProperties"/>
    </bean>
  
    <!--配置全域性變數-->
    <bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="singleton" value="true"/>
        <property name="properties">
              <props>
              		<prop key="csdn.url">${csdn.url}</prop>
              </props>
        </property>
    </bean>