To inject the Properies file method using spring:
1, SRC in a new settings.properties file, the contents are as follows:
Db_driverclassname=com.mysql.jdbc. driverdb_url=jdbc:mysql://127.0. 0.1/testdb_username=Rootdb_password=roottest_username=robintest_age =
2. Add this paragraph to spring's applicationcontext.xml:
<BeanID= "Configproperties"class= "Org.springframework.beans.factory.config.PropertiesFactoryBean"> < Propertyname= "Locations"> <List> <value>Classpath*:settings.properties</value> </List> </ Property> </Bean> <BeanID= "Propertyconfigurer"class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> < Propertyname= "Ignoreresourcenotfound"value= "false" /> < Propertyname= "Properties"ref= "Configproperties" /> </Bean>
The following spring's XML configuration can be used directly in this way:
<BeanID= "DataSource"class= "Org.springframework.jdbc.datasource.DriverManagerDataSource"> < Propertyname= "Driverclassname"value= "${db_driverclassname}"/> < Propertyname= "url"value= "${db_url}" /> < Propertyname= "username"value= "${db_username}" /> < Propertyname= "Password"value= "${db_password}" /> </Bean>
3. Create a new Class:Settings.java
PackageCom.my.common;ImportOrg.springframework.beans.factory.annotation.Value;Importorg.springframework.stereotype.Component; @Component Public classSettings {Private StaticSettings instance; Public StaticSettings getinstance () {returninstance; } PublicSettings () {instance= This; } @Value ("#{configproperties[' Test_username '}") PrivateString UserName; @Value ("#{configproperties[' Test_age '}") Private intAge ; PublicString GetUserName () {returnUserName; } Public voidsetusername (String userName) { This. UserName =UserName; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; }}
You can then call this in the code:
Settings.getinstance (). GetUserName ()
[Spring]-Property injection