1. Latar belakang
Baru -baru ini, selama proses pengembangan proyek, saya mengalami masalah yang saya butuhkan untuk mendefinisikan beberapa variabel khusus dalam file properti untuk membaca dinamis dan mengubah variabel program Java, dan tidak perlu lagi memodifikasi kode. Saya mengambil kesempatan ini untuk memilah dan menganalisis konten file properti dalam proyek pengembangan terintegrasi Spring+SpringMVC+MyBatis melalui program Java, dan membagikannya terlebih dahulu dengan Anda.
2. Pengenalan Lingkungan Proyek
Tiga atau lima cara untuk mengimplementasikannya
Metode 1. Muat konten dalam file konfigurasi jdbc.properties melalui konteks: property-placeHolder
<Konteks: Lokasi pemegang tempat properti = "classpath: jdbc.properties" abaikan-tidak dapat diselesaikan = "true"/>
Konfigurasi di atas setara dengan konfigurasi berikut, yang merupakan penyederhanaan dari konfigurasi berikut
<bean id = "PropertyConfigurer"> <Property Name = "IGNUnResolVablePlaceHolders" value = "true"/> <Property name = "Lokasi"> <list> <value> classpath: jdbc.properties </value> </list> </propert> </bean>
Catatan: Dengan cara ini, jika Anda memiliki konfigurasi berikut dalam file spring-mvc.xml, Anda tidak boleh kehilangan bagian merah berikut, tentang fungsi dan prinsipnya.
<!-Mengkonfigurasi pemindaian komponen, hanya anotasi pengontrol yang dipindai dalam wadah springmvc-> <konteks: komponen-scan-package = "com.hafiz.www" penggunaan-default-filters = "false"> <contact: include-filter type = "annotation" Expression = "org.springfring.steretyple.stersteran.sterteran =" orgrcon-sclcoryprecypron. "
Metode 2. Injeksi menggunakan anotasi, terutama menyuntikkan nilai yang sesuai dalam file properti menggunakan anotasi dalam kode Java.
<bean id = "prop"> <!- Ini adalah kelas PropertiesFactoryBean. Ini juga memiliki properti lokasi, yang juga menerima array, seperti halnya di atas-> <name properti = "Lokasi"> <r array> <value> classpath: jdbc.properties </ value> </r array> </prop Property> </ bean>
Metode 3. Gunakan tag util: properti untuk mengekspos konten dalam file properti
<util: properti ID = "PropertiesReader" Lokasi = "ClassPath: jdbc.properties"/>
Catatan: Menggunakan konfigurasi baris di atas, Anda perlu mendeklarasikan bagian merah berikut di header file spring-dao.xml
<beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: konteks = "http: xmlns: util = "http://www.springframework.org/schema/util" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/www.springframework.org/schema http://www.springframework.org/schema/util/spring-util.xsd ">
Metode 4. Mengekspos properti ke properti subkelas khusus untuk digunakan dalam program saat memuat konteks melalui propertiPlaceHolderConfigurer
<bean id = "PropertyConfigurer"> <name properti = "abaikan yang dapat diselidiki tempat" value = "true"/> <name properti = "ignoreresourcenotfound" value = "true"/> <name properti = "lokasi"> <cist> <value> classpath: jdbc.properties </value> </list> <value> classpath: jdbc.properties </value> </list> <value> classpath: jdbc.properties </value> </list> <value> classpath: jdbc.properties </value> </list> <value> classpath: jdbc.properties </value> </list> propert
Deklarasi Property Configurer kelas khusus adalah sebagai berikut:
package com.hafiz.www.util;import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;import java.util.properties;/*** Desc: Properties Configuration File Reading Class* Dibuat oleh hafiz.zhang pada 2016/9/14. */Kelas Publik Property Configurer memperluas propertiPlaceHolderConfigurer {private properties props; // Akses Properties Konfigurasi File Kunci-Nilai Hasil @Override Printer ProcessProperties Proses (ConfigurableListableBeanFactory BeanFactoryToprocess, Properties Props) Melempar BeanSexception {Super.ProcessProperties (BeanFactoryTopRocess, prop); this.props = props; } public string getProperty (tombol string) {return this.props.getProperty (key); } public String getProperty (tombol string, string defaultValue) {return this.props.getProperty (key, defaultValue); } setProperty objek publik (tombol string, nilai string) {return this.props.setProperty (key, value); }}Cara menggunakan: Cukup gunakan injeksi anotasi @Autowired di kelas yang perlu Anda gunakan.
Metode 5. Kustomisasi Kelas Alat Propertyutil, dan baca konten file properti di blok kode statis statis kelas dan simpan di properti statis untuk digunakan oleh program lain.
Paket com.hafiz.www.util; impor org.slf4j.logger; impor org.slf4j.loggerfactory; impor java.io.*; impor java.util.properties;/*** desc: properti alat perolehan file* dibuat oleh hafiz.zhang on 2016/9/ desc: Properties Acquisition Tool Kelas* Dibuat oleh Hafiz.zang on 2016/9/ Desc: Properties. */kelas publik PropertyUtil {private static final Logger Logger = loggerFactory.getLogger (propertiTutil.class); Alat peraga properti statis pribadi; static {loadProps (); } Sinkronisasi statis void loadProps () {logger.info ("Mulai memuat konten file properti ......"); alat peraga = properti baru (); Inputstream in = null; Coba {<!-Tipe Pertama, dapatkan aliran file Properties melalui class loader-> di = Propertyutil.class.getClassLoader (). GetResourCeAsstream ("jdbc.properties"); <!-Tipe Kedua, dapatkan aliran file Properties melalui kelas-> // di = PropertyUtil.class.getResourCeAsstream ("/jdbc.properties"); props.load (dalam); } catch (FileNotFoundException e) {logger.error ("jdbc.properties file tidak ditemukan"); } catch (ioException e) {logger.error ("ioException muncul"); } akhirnya {coba {if (null! = in) {in.close (); }} catch (ioException e) {logger.error ("Pengecualian ditutup dengan stream file jdbc.properties tertutup"); }} logger.info ("Memuat konten file properti ........."); logger.info ("Konten File Properties:" + Props); } public static String getProperty (tombol string) {if (null == props) {loadProps (); } return props.getProperty (key); } public static string getProperty (tombol string, string defaultValue) {if (null == props) {loadProps (); } return props.getProperty (key, defaultValue); }}Catatan: Dengan cara ini, ketika kelas dimuat, ia akan secara otomatis membaca konten file konfigurasi di lokasi yang ditentukan dan menyimpannya ke properti statis, yang efisien dan nyaman, dan dapat dimuat pada satu waktu dan digunakan beberapa kali.
4. Tindakan Pencegahan dan Saran
Tiga metode pertama kaku dalam lima metode di atas. Dan jika Anda ingin menggunakannya dalam kacang dengan anotasi @Controller, Anda perlu mendeklarasikannya di file konfigurasi SpringMVC Spring-mvc.xml. Jika Anda ingin menggunakannya dalam kacang dengan @Service, @respository, dll. Anda perlu mendeklarasikannya di Spring.xml dalam file konfigurasi Spring.
Saya pribadi merekomendasikan metode konfigurasi keempat dan kelima. Yang kelima adalah yang terbaik. Bahkan tidak perlu disuntikkan ke objek seperti alat, dan secara langsung memanggil metode statis untuk akuisisi, dan hanya memuatnya sekali, yang juga sangat efisien. Selain itu, tiga metode pertama tidak terlalu fleksibel, dan nilai kunci @Value diperlukan.
5. Tes untuk memverifikasi apakah tersedia
1. Pertama kami membuat propertiesService
Paket com.hafiz.www.service;/** * Desc: Java Program mendapatkan layanan konten file properti * dibuat oleh hafiz.zhang pada 2016/9/16. */Antarmuka Public PropertiesService {/** * Metode implementasi pertama mendapatkan nilai tombol yang ditentukan dalam file properti * * @return */string getPreperyByFirstway (); / ** * Metode implementasi kedua mendapatkan nilai tombol yang ditentukan dalam file properti * * @return */ string getProperyBySecondWay (); / ** * Metode implementasi ketiga mendapatkan nilai tombol yang ditentukan dalam file properti * * @return */ string getPreperyByTheRdway (); / ** * Metode implementasi keempat mendapatkan nilai tombol yang ditentukan dalam file Properties * * @param Key * * @return */ String getPreperyByFourthway (tombol string); / ** * Metode implementasi keempat mendapatkan nilai tombol yang ditentukan dalam file properti * * @param Key * * @param defaultValue * * @return */ string getPreperyByFourthway (tombol string, string defaultValue); / ** * Metode implementasi kelima mendapatkan nilai tombol yang ditentukan dalam file properti * * @param Key * * @return */ String getPreperyByFifthway (tombol string); / ** * Metode implementasi kelima untuk mendapatkan nilai tombol yang ditentukan dalam file properti * * Kunci @param * * @param defaultValue * * @return */ string getPreperyByFifthway (tombol string, string defaultValue);}2. Buat dan terapkan kelas PropertiesServiceImpl
Paket com.hafiz.www.service.impl; import com.hafiz.www.service.propertiesservice; import com.hafiz.www.util.propertyconfigurer; import com.hafiz.www.util.propertyutil; impor org.springfringfring.pringring.bane.bane. org.springframework.beans.factory.annotation.value; impor org.springframework.stereotype.service;/*** Desc: Program Java memperoleh kelas implementasi layanan dari layanan yang memperoleh konten dari file properti* dibuat oleh Hafiz.zhang pada 2016/9/16. */ @ServicePublic Class PropertiesServiceImpl mengimplementasikan 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 getProperyByTheRdway () {return testDatabyTheRd; } @Override public String getProperyByByFourWay (tombol string) {return pc.getProperty (key); } @Override public String getProperyByBoUrthWay (tombol string, string defaultValue) {return pc.getProperty (key, defaultValue); } @Override Public String getProperyByFifthway (tombol string) {return propertyutil.getPropery (key); } @Override public String getProperyByFifthway (tombol string, string defaultValue) {return propertieutil.getProperty (key, defaultValue); }}3. Kelas Pengontrol PropertyController
Paket com.hafiz.www.controller; import com.hafiz.www.service.propertiesservice; import com.hafiz.www.util.propertyutil; impor org.spramework.beans.factory.annotation.autowired; impor org.spramework.beans.factory.annotation.autowired; import org.spramework.beans.factory.annotation.Autowired; impor org.spramework.bean.factory. org.springframework.web.bind.annotation.pathvariable; impor org.springframework.web.bind.annotation.Requestmapping; impor org.springframework.web.bind.annotation.RequestMethod; impor org.springframework.wind.notation.roBese.binpety; Pengontrol* Dibuat oleh Hafiz.zhang pada 2016/9/16. */@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/ketiga", Method = requestMethod.get) @ResponseBody Public String getPropertyByTheRdway () {return ps.getProperyByTheDway (); } @RequestMapping (value = "/way/fourth/{key}", method = requestMethod.get) @ResponseBody string publik getPropertyByFourthway (@pathvariable ("key") string Key) {return ps.getproperyByFourway (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 file
jdbc.driver = com.mysql.jdbc.driverjdbc.url = jdbc: mysql: //192.168.1.196: 3306/dev? UseUnicode = true & characterencoding = UTF-8JDBC.username = rootjdbc.passer = ctive = 200jdbc.minidle = 5jdbc.initialsize = 1jdbc.maxwait = 60000jdbc.TimeBetweenevictionRunsmillis = 60000jdbc.minevictableImemillis = 300000jdbc.validationQuery = 1 dari t_userjdbc.testwhileIdle = trueJdbc.testonreturn = falseJdbc.poolpreparedStatements = trueJdbc.MaxPoolPreparedStatementPerConnectionSize = 20jdbc.filters = stat#uji data = com.hafiz.www
5. Diagram hasil proyek
6. Unduh Proyek: Demo http://xiazai.vevb.com/201612/yuanma/propertiesconfigurer_jb51.zip
7. Hasil tes
Metode pertama
Cara kedua
Cara ketiga
Metode keempat
Metode kelima
6. Ringkasan
Melalui tinjauan dan pengujian ini, kami memahami peran dan prinsip hubungan wadah orangtua-anak antara Spring dan SpringMVC dan atribut penggunaan-default-filters yang paling mudah diabaikan saat memindai konteks: paket tag pemindaian komponen. Dapat menemukan dan menyelesaikan masalah yang lebih baik lagi. Bagaimanapun, bagus ~~~
Di atas adalah semua konten artikel ini. Saya berharap ini akan membantu untuk pembelajaran semua orang dan saya harap semua orang akan lebih mendukung wulin.com.