spring 的 PropertyPlaceholderConfigurer讀取的屬性怎么訪問 (java訪問方式,不是xml中的占位符哦)及此類的應用


一、1.占位符的應用:(@Autowired注解方式,不需要建立set與get方法了,xml注入也不需要寫了)

http://www.cnblogs.com/susuyu/archive/2012/09/10/2678458.html

 

二、

2、java方式訪問(已經驗證過好用)

1、通過spring配置properties文件

 

[java]  <bean id="propertyConfigurer"      class="com.tjsoft.base.util.CustomizedPropertyPlaceholderConfigurer">      <property name="ignoreResourceNotFound" value="true" />      <property name="locations">          <list>              <value>/WEB-INF/config/jdbc.properties</value>              <value>/WEB-INF/config/mail.properties</value>              <value>/WEB-INF/config/system.properties</value>          </list>      </property>  </bean> 

其中class為自己定義的類

2、自定義類CustomizedPropertyPlaceholderConfigurer

[java]  import java.util.HashMap;  import java.util.Map;  import java.util.Properties;    import org.springframework.beans.BeansException;  import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;  import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;    /**  * 自定義PropertyPlaceholderConfigurer返回properties內容  *   * @author LHY 2012-02-24  *   */  public class CustomizedPropertyPlaceholderConfigurer extends          PropertyPlaceholderConfigurer {        private static Map<String, Object> ctxPropertiesMap;        @Override      protected void processProperties(              ConfigurableListableBeanFactory beanFactoryToProcess,              Properties props) throws BeansException {          super.processProperties(beanFactoryToProcess, props);          ctxPropertiesMap = new HashMap<String, Object>();          for (Object key : props.keySet()) {              String keyStr = key.toString();              String value = props.getProperty(keyStr);              ctxPropertiesMap.put(keyStr, value);          }   www.2cto.com     }        public static Object getContextProperty(String name) {          return ctxPropertiesMap.get(name);      }    }   

 

這樣就可以通過CustomizedPropertyPlaceholderConfigurer類來獲取properties屬性文件中的內容了

3、如何獲取屬性文件的內容

String host =  (String) CustomizedPropertyPlaceholderConfigurer.getContextProperty("mail.smtp.host");

 

三、未驗證,不知道好用不

action也是spring配置的bean嗎?
是的話,直接注入就行了。
<bean id="actionname" class="com.MyAction">
   <property name="property1" value="${configed.property1}"/>
</bean>

如果不是,可以將這個property注入到System.properties中去
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
    depends-on="PlaceholderConfigurer">
<property name="targetClass">
<value>java.lang.System</value>
</property>
<property name="targetMethod">
<value>setProperty</value>
</property>
<property name="arguments">
<list>
<value>property1</value>
<value>${configed.property1}"</value>
</list>
</property>
</bean
然后在action中使用System.getProperty("property1")


免責聲明!

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



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