Use the Properties file in Spring, springproperties
Spring provides a tool class for loading Properties files: org. springframework. beans. factory. config. PropertyPlaceholderConfigurer.
When the Spring container is started, use the built-in bean to load the property file information. Add the following to bean. xml:
<! -- Spring property loader, Loading properties in the properties file --> <bean id = "propertyConfigurer" class = "org. springframework. beans. factory. config. propertyPlaceholderConfigurer "> <property name =" location "> <value>/WEB-INF/configInfo. properties </value> </property> <property name = "fileEncoding" value = "UTF-8"/> </bean>
One of the following ways to use attribute information after loading is to directly reference value based on the key of attribute information in other bean definitions. For example, the mail sender bean configuration is as follows:
<! -- Send email --> <bean id = "mailSender" class = "org. springframework. mail. javamail. javaMailSenderImpl "> <property name =" host "> <value >$ {email. host} </value> </property> <property name = "port"> <value >$ {email. port} </value> </property> <property name = "username"> <value >$ {email. username} </value> </property> <property name = "password"> <value >$ {email. password} </value> </property> <property name = "javaMailProperties"> <props> <prop key = "mail. smtp. auth "> true </prop> <prop key =" sendFrom ">$ {email. sendFrom} </prop> </props> </property> </bean>
Another method is to obtain the configured attribute information in the code. You can define a javabean: ConfigInfo. java, uses annotations to inject the property information to be used in the Code. For example, the following information in the property file must be obtained and used in the Code:
# Save file. savePath = D:/test/# backup path of the generated file. after use, move the corresponding file to this directory file. backupPath = D:/test bak/
ConfigInfo. java:
@ Component ("configInfo") public class ConfigInfo {@ Value ("$ {file. savePath} ") private String fileSavePath; @ Value (" $ {file. backupPath} ") private String fileBakPath; public String getFileSavePath () {return fileSavePath;} public String getFileBakPath () {return fileBakPath;} inject the ConfigInfo object with annotations in the business class bo: @ Autowiredprivate ConfigInfo configInfo; it must be in bean. add a component scanner to xml for automatic injection in Annotation mode: <context: component-scan base- Package = "com. my. model"/> (the above package model contains the ConfigInfo class ).
The get method is used to obtain the corresponding property information. The advantage is that it is easy to use in the Code. The disadvantage is that if new property information is required in the code, you need to add and modify ConfigInfo. java accordingly.