1。背景
最近、プロジェクト開発プロセス中に、Javaプログラムの変数を動的に読み、変更するためにプロパティファイルにいくつかのカスタム変数を定義するために必要な問題に遭遇し、コードを変更するためにもはや必要ありませんでした。この機会を利用して、Javaプログラムを通じてSpring+SpringMVC+MyBatisの統合開発プロジェクトでプロパティファイルのコンテンツを整理して分析し、最初にあなたと共有しました。
2。プロジェクト環境の紹介
実装する3つまたは5つの方法
方法1。コンテストファイルにコンテンツをロードしますjdbc.propertiesを介して:プロパティプレイスホルダー
<コンテキスト:プロパティプレイスホルダーlocation = "classpath:jdbc.properties" Ingrore-unresolvable = "true"/>
上記の構成は次の構成と同等であり、これは次の構成の簡素化です
<bean id = "propertyconfigurer"> <プロパティ名= "IngroreUnResolvablePlaceHolders" value = "true"/> <property name = "locations"> <list> <value> classpath:jdbc.properties </value> </list> </property> </bean>
注:このように、Spring-MVC.XMLファイルに次の構成がある場合、その機能と原則について、次の赤い部分を見逃さないでください。
<!-- Configure component scanning, only Controller annotations are scanned in springmvc container--><context:component-scan base-package="com.hafiz.www" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.steretype.Controller"/></context:component-scan>
方法2。注釈を使用した注入、主にJavaコードの注釈を使用してプロパティファイルに対応する値を注入します。
<bean id = "prop"> <! - これはPropertiesFactoryBeanクラスです。また、上記と同じように、配列を受け取る場所もあります。
方法3。util:プロパティタグを使用して、プロパティファイルのコンテンツを公開します
<util:Properties id = "PropertiesReader" location = "classpath:jdbc.properties"/>
注:上記のライン構成を使用すると、Spring-dao.xmlファイルのヘッダーで次の赤い部分を宣言する必要があります
<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:util = "http://www.springframework.org/schema/util" xsi:schemalocation = " http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context-/spring-context-/spring-contex http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
方法4。プロパティPlacePlaceHolderConFigurerを介してコンテキストをロードするときに、プログラムで使用するためにカスタムサブクラスのプロパティにプロパティを公開する
<bean id = "propertyconfigurer"> <プロパティ名= "IngroreUnResolvable PlaceHolders" value = "true"/> <Property name = "ingoreresourcenotfound" value = "true"/> <property names = "locations"> <propert> classpath:jdbc.properties </value> </ligp> </propertion> </propitial> </bean>
カスタムクラスPropertyConfigurerの宣言は次のとおりです。
パッケージcom.hafiz.www.util; Import org.springframework.beans.beansexception; Import org.springframework.beans.factory.configurablelistablebeanfactory; import org.springframework.beans.factory.config. DESC:Properties Configuration File Readingクラス* 2016/9/14にHafiz.zhangによって作成されました。 */public class propertyconfigurerは、propertyplaceholderconfigurerを拡張します{private properties props; //プロパティ構成ファイルにアクセスキーバリュー@OverrideプロテクションVoid ProcessProperties(configurableLelistableBeanFactory BeanFactoryToprocess、Properties Props)Throws BeanSexception {super.processprocess(BeanFactoryToprocess、Props); this.props = props; } public string getProperty(string key){return this.props.getProperty(key); } public string getProperty(String key、string defaultValue){return this.props.getProperty(key、defaultValue); } public Object setProperty(string key、string value){return this.props.setProperty(key、value); }}使用方法:使用する必要があるクラスで@Autowiredアノテーションインジェクションを使用するだけです。
方法5。ツールクラスのPropertyUtilをカスタマイズし、クラスの静的な静的コードブロックのプロパティファイルコンテンツを読み取り、他のプログラムで使用するために静的プロパティに保存します。
パッケージcom.hafiz.www.util; Import org.slf4j.logger; Import org.slf4j.loggeractory; import java.io。*; Import java.util.properties;/** desc:hafiz.zhangによって作成されたプロパティファイル取得ツールクラス* */public class propertyutil {private static final logger logger = loggerfactory.getLogger(propertutil.class);プライベート静的プロパティの小道具; static {loadprops(); } Synchronized static private void loadprops(){logger.info( "プロパティのロードファイルコンテンツのロードを開始......"); props = new Properties(); inputstream in = null; try {<! - 最初のタイプ、クラスローダーを介してプロパティファイルストリームを取得 - > in = propertyutil.class.getClassLoader()。 <! - 2番目のタイプ、クラスを介してプロパティファイルストリームを取得 - > // in = propertyutil.class.getResourceasStream( "/jdbc.properties"); props.load(in); } catch(filenotfoundexception e){logger.error( "jdbc.propertiesファイルが見つかりません"); } catch(ioException e){logger.error( "ioException essight"); }最後に{try {if(null!= in){in.close(); }} catch(ioException e){logger.error( "jdbc.propertiesファイルストリームが閉じた場合の例外閉じています"); }} logger.info( "プロパティファイルのコンテンツのロード........."); logger.info( "プロパティファイルコンテンツ:" + props); } public static string getProperty(string key){if(null == props){loadprops(); } props.getProperty(key)を返します。 } public static string getProperty(string key、string defaultValue){if(null == props){loadprops(); } props.getProperty(key、defaultValue)を返します。 }}注:このようにして、クラスがロードされると、指定された場所の構成ファイルコンテンツを自動的に読み取り、それを静的プロパティに保存します。これは効率的で便利で、一度にロードされ、複数回使用できます。
4。予防策と提案
上記の5つの方法では、最初の3つの方法は剛性です。また、@Controller Annotationを備えたBeanでそれらを使用する場合は、SpringMVCの構成ファイルSpring-MVC.XMLでそれらを宣言する必要があります。 @Service、@RespositoryなどのBeanでそれらを使用する場合は、Spring.xmlでSpringの構成ファイルで宣言する必要があります。
個人的には、4番目と5番目の構成方法をお勧めします。 5番目は最高です。ツールのようなオブジェクトに注入する必要さえありません。また、獲得の静的方法を直接呼び出し、1回のみロードします。これも非常に効率的です。さらに、最初の3つの方法はあまり柔軟ではなく、@Valueの重要な値が必要です。
5。利用可能かどうかを確認するためにテストします
1.最初にPropertiESServiceを作成します
パッケージcom.hafiz.www.service;/** * desc:javaプログラムは、2016/9/16にhafiz.zhangによって作成されたプロパティファイルのコンテンツのサービスを取得します。 */public Interface PropertiesService {/** *最初の実装メソッドは、プロパティファイルの指定されたキーの値を取得します * * @return */string getProperyByFirstway(); / ** * 2番目の実装メソッドは、プロパティファイルに指定されたキーの値を取得します * * @return */ string getProperyBysecondway(); / ** * 3番目の実装メソッドは、プロパティファイルに指定されたキーの値を取得します * * @return */ string getProperyByThirdway(); / ** * 4番目の実装メソッドは、プロパティファイルの指定されたキーの値を取得します * * @param key * * @return */ string getProperyByFourthway(String Key); / ** * 4番目の実装メソッドは、プロパティファイルの指定されたキーの値を取得します * * @param key * * @param defaultValue * * @return */ string getProperyByFourthway(String Key、String DefaultValue); / ** * 5番目の実装メソッドは、プロパティファイルの指定されたキーの値を取得します * * @param key * * @return */ string getProperyByFifthway(String Key); / ** *プロパティファイルで指定されたキーの値を取得する5番目の実装方法 * * @param key * * @param defaultValue * * @return */ string getProperyByFifthway(String Key、String DefaultValue);}2。クラスPropertieserviceImplを作成および実装します
パッケージcom.hafiz.www.service.impl; import com.hafiz.www.service.propertiesservice; Import com.hafiz.www.util.propertyconfigurer; Import com.hafiz.www.util.propertyutil; Import org.springframework.springframework.bbeans.Annotation org.springframework.beans.factory.annotation.value; import org.springframework.stereotype.service;/*** desc:javaプログラムは、2016/9/19/19/19/19/19/19/19/19/19/19/9/19/19/19/19/19/9/19/9/19/9/16によって作成されたプロパティファイルのコンテンツを取得するサービスのサービス実装クラスを取得します。 */ @servicePublic Class PropertiESServiceImpl PropertiESService {@Value( "$ {test}")private string testdatabyfirst; @value( "#{prop.test}")private string testdatabysecond; @value( "#{propertiesReader [test]}")private string testdatabythird; @Autowired Private PropertyConfigurer PC; @Override public String getProperyByFirstway(){return testDataByfirst; } @Override public String getProperyBysecondway(){return testDatabySecond; } @Override public String getProperyByThirdway(){return testDataBythird; } @Override public String getProperyByFourthway(String key){return pc.getProperty(key); } @Override public String getProperyByFourthway(String Key、String DefaultValue){return PC.GetProperty(key、defaultValue); } @Override public String getProperyByFifthway(String Key){return PropertyUtil.getPropery(key); } @Override public String getProperyByFifthway(String Key、String DefaultValue){return PropertyUtil.getProperty(key、defaultValue); }}3。コントローラークラスPropertyController
package com.hafiz.www.controller;import com.hafiz.www.service.PropertiesService;import com.hafiz.www.util.PropertyUtil;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.pathvariable; Import org.springframework.web.bind.annotation.Requestmapping; Import org.springframework.web.bind.annotation.Requestmethod; Import org.springframework.** desconse.** desconwork.** desconsebows Controller* 2016/9/16にHafiz.zhangによって作成されました。 */@controller@requestMapping( "/prop")public class propertycontroller {@autowired private propertiesservice ps; @RequestMapping(value = "/way/first"、method = requestmethod.get)@responsebody public string getPropertyByFirstway(){return ps.getProperyByFirstway(); } @requestMapping(value = "/way/second"、method = requestmethod.get)@responsebody public string getPropertyBysecondway(){return ps.getProperyBysecondway(); } @RequestMapping(value = "/way/third"、method = requestmethod.get)@responsebody public string getPropertyByThirdway(){return ps.getProperyByThirdway(); } @RequestMapping(value = "/way/fourth/{key}"、method = requestmethod.get)@responsebodyパブリック文字列getPropertybyfourthway( @pathvariable( "key")string key){return ps.getProperyByFourthway(key、 "defaultValue"); } @RequestMapping(value = "/way/fifth/{key}"、method = requestmethod.get)@responsebody public string getPropertybyfifthway( @pathvariable( "key")string key){return propertyutil.getProperty(key、 "defaultValue"); }}4.jdbc.propertiesファイル
jdbc.driver = com.mysql.jdbc.driverjdbc.url = jdbc:mysql://192.168.1.196:3306/dev?useunicode = true&charaterencoding = utf-8jdbc.username = rootjdbc.password = 123456jdbc.max. ctive = 200jdbc.minidle = 5jdbc.initialsize = 1jdbc.maxwait = 60000jdbc.timebetweenevictionrunsmillis = 60000jdbc.minevictableidletimemillis = 300000jdbc.validation = select 1 from t_userjdbc.testwhileidle = truejdbc.testonreturn = falsejdbc.poolpreparedstatements = truejdbc.maxpoolpreparedStatementperconnectionsize = 20jdbc.filters = stat#test dataTest = com.hafiz.www
5.プロジェクト結果図
6.プロジェクトのダウンロード:Demo http://xiazai.vevb.com/201612/yuanma/propertiesconfigurer_jb51.zip
7。テスト結果
最初の方法
2番目の方法
3番目の方法
4番目の方法
5番目の方法
6。概要
このレビューとテストを通じて、SpringとSpringMVCの間の親子コンテナ関係の役割と原則、およびコンテキストをスキャンするときに最も簡単に見落とされるUse-Default-Filters属性を理解しています:Component-Scanタグパッケージ。再び遭遇した問題をより適切に見つけて、迅速に解決できるようになります。とにかく、素晴らしい~~~
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。