Spring loads configuration file xml and properties

The Spring configuration file is the core of the project that integrates the Spring framework. Where does the engine start and what operations are performed in the middle. Let’s talk about its execution process.

Loading the xml situation
The container first loads web.xml

and then the registration of applicationContext.xml in web.xml

One way is to add the servlet ContextLoaderServlet

1 <context-param> 
2 <param-name>contextConfigLocation</param-name> 
3 < param-value>/WEB-INF/applicationContext.xml</param-value> 
4 </context-param> 
5 <servlet> 
6 <servlet-name>context</servlet-name> 
7 <servlet-class> 
8 org .springframework.web.context.ContextLoaderServlet  
9 </servlet-class> 
10 <load-on-startup>0</load-on-startup> 
11 < 



Another is to add ContextLoaderListener this listener


1 <context-param> 
2 <param-name>contextConfigLocation</param-name> 
3 <param-value>/WEB-INF/applicationContext.xml</param-value> 
4 < /context-param> 
5  
6 <listener> 
7 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
8 </listener> 



ContextLoaderServlet and ContextLoaderListener both create an object of ContextLoader first, and then call Its initWebApplicationContext method initializes WebApplicationContext to obtain an object;


spring loads multiple configuration files, in web.xml

1 <context-param>
2 <param-name>contextConfigLocation</param-name>
3 <param-value>classpath*: spring/*.xml< /param-value>
4 </context-param>
5
6 <servlet>
7 <servlet-name>SpringContextServlet</servlet-name>
8 <servlet-class>
9 org.springframework.web.context.ContextLoaderServlet
10 </servlet-class>
11 <load-on-startup>3< /load-on-startup>
12 </servlet>

Loading Properties

A system usually has the following configuration files in the form of Properties
1. The database configuration file demo-db.properties:
Properties code Collection code
database.url=jdbc: mysql://localhost/smaple 
database.driver=com.mysql.jdbc.Driver 
database.user=root 
database.password=123 

2. Message service configuration file demo-mq.properties:
Properties code Collection code
#congfig of ActiveMQ 
mq.java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory 
mq.java.naming.provider.url=failover:(tcp://localhost:61616?soTimeout=30000&connectionTimeout=30000)?jms.useAsyncSend =true&timeout=30000 
mq.java.naming.security.principal= 
mq.java.naming.security.credentials= 
jms.MailNotifyQueue.consumer=5 

3. Remote call configuration file demo-remote.properties:
Properties code Favorite code
remote. ip=localhost 
remote.port=16800 remote.serviceName 
=test 

1. Multiple Properties configuration files need to be loaded in the system
Application scenario: There is more than one Properties configuration file, and multiple Properties files need to be loaded at the same time when the system starts.
Configuration method:
Xml code Collection code
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation=" 
    http://www .springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
     
    <!-- Read multiple configuration files into the container and hand them over to Spring for management --> 
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
        <property name="locations"> 
           <list> 
              <!-- Multiple addressing methods are supported here: classpath and file --> 
              <value>classpath:/opt/demo/config/demo-db.properties</value> 
              <!  -- It is recommended to use the file method to introduce, so that the configuration and code can be separated -->
              <value>file:/opt/demo/config/demo-mq.properties</value> 
              <value>file:/opt/demo/config/demo-remote.properties</value> 
            </list> 
        </property> 
    </bean> 
     

    <!-- 使用MQ中的配置 --> 
    <bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate"> 
        <property name="environment"> 
            <props> 
                <prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop> 
                <prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop> 
                <prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop> 
                <prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop> 
                <prop key="userName">${mq.java.naming.security.principal}</prop> 
                <prop key="password">${mq.java.naming.security.credentials}</prop> 
            </props> 
        </property> 
    </bean> 
</beans> 
我们也可以将配置中的List抽取出来:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
     
    <!-- put multiple configuration file locations into a list--> 
    <bean id="propertyResources" class="java.util.ArrayList"> 
        <constructor-arg> 
            <list> 
              <!-- here supports multiple Addressing mode: classpath and file --> 
              <value>classpath:/opt/demo/config/demo-db.properties</value> 
              <!-- It is recommended to use file introduction, which can separate configuration and code- -> 
              <value>file:/opt/demo/config/demo-mq.properties</value> 
              <value>file:/opt/demo/config/demo-remote.properties</value> 
            </list> 
        </ constructor-arg> 
    </bean> 
     
    <!-- Read the configuration file into the container and hand it over to Spring management --> 
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
        <property name="locations" ref="propertyResources" /> 
    </bean> 
     
    <!-- 使用MQ中的配置 --> 
    <bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate"> 
        <property name="environment"> 
            <props> 
                <prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop> 
                <prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop> 
                <prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop> 
                <prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop> 
                <prop key="userName">${mq.java.naming.security.principal} </prop> 
                <prop key="password">${mq.java.naming.security.credentials}</prop> 
            </props> 
        </property> 
    </bean> 
</beans> 

Second, integrate multiple projects Multiple scattered Properties
application scenarios: There are multiple configuration files in the engineering group, but these configuration files are used in multiple places, so they need to be loaded separately.
The configuration is as follows:
Xml code Collection code
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http: //www.w3. 

    xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
     
    <!-- the DB property configuration file Place the location in the list --> 
    <bean id="dbResources" class="java.util.ArrayList"> 
        <constructor-arg> 
        <list> 
            <value>file:/opt/demo/config/demo-db.properties </value> 
        </list> 
        </constructor-arg> 
    </bean> 
 
    <!-- put the MQ properties configuration file location into the list --> 
    <bean id="mqResources" class="java.util.ArrayList "> 
        <constructor-arg> 
        <list> 
            <  value>file:/opt/demo/config/demo-mq.properties</value> 
        </list> 
        </constructor-arg> 
    </bean> 
     
    <!-- 用Spring加载和管理DB属性配置文件 --> 
    <bean id="dbPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
        <property name="order" value="1" /> 
        <property name="ignoreUnresolvablePlaceholders" value="true" />  
        <property name="locations" ref="dbResources" /> 
    </bean> 
     
    <!-- 用Spring加载和管理MQ属性配置文件 --> 
    <bean id="mqPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
        <property name="order" value="2" /> 
        <property name="ignoreUnresolvablePlaceholders" value="true" />  
        <property name="locations" ref="mqResources" /> 
    </bean> 
     
    <!-- 使用DB中的配置属性 --> 
    <bean id="rmsDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"  
        p:driverClassName="${demo.db.driver}" p:url="${demo.db.url}" p:username="${demo.db.username}"  
        p:password="${demo.db.password}" pp:maxActive="${demo.db.maxactive}"p:maxWait="${demo.db.maxwait}"  
        p:poolPreparedStatements="true" p:defaultAutoCommit="false"> 
    </bean> 
     
    <!-- 使用MQ中的配置 --> 
    <bean id="MQJndiTemplate" class="org.springframework.jndi.JndiTemplate"> 
        <property name="environment"> 
            <props> 
                <prop key="java.naming.factory.initial">${mq.java.naming.factory.initial}</prop> 
                <prop key="java.naming.provider.url">${mq.java.naming.provider.url}</prop> 
                <prop key="java.naming.security.principal">${mq.java.naming.security.principal}</prop> 
                <prop key="java.naming.security.credentials">${mq.java.naming.security.credentials}</prop> 
                <prop key="userName">${mq.java.naming.security.principal}</prop> 
                <prop key="password">${mq.java.naming.security.credentials}</prop> 
            </props> 
        </property> 
    </bean> 
</beans> 
Note: The order property represents its loading order, and ignoreUnresolvablePlaceholders is whether to ignore unresolvable Placeholders. If multiple PropertyPlaceholderConfigurers are configured, it needs to be set to true. These two parameters must be set in this way here.

3. Directly inject the value in the Properties configuration file into the Bean
Application scenario: The Bean needs to directly inject the value in the Properties configuration file. For example, the following code needs to obtain the value in the above demo-remote.properties:
Java code Favorite code
public class Client() { 
    private String ip; 
    private String port; 
    private String service; 
}  The
configuration is as follows:
Xml code Favorite code
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema /beans</a>" 
xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance"> 
xmlns:util="<a href="http://www.springframework.org/schema/util">http://www.springframework.org/schema/util</a>" 
xsi:schemaLocation=" 
<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a> <a href="http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">http://www.springframework.org/schema/beans/spring-beans-3.0.xsd</a> 
<a href="http://www.springframework.org/schema/util">http://www.springframework.org/schema/util</a> <a href="http://www.springframework.org/schema/util/spring-util-3.0.xsd">http://www.springframework.org/schema/util/spring-util-3.0.xsd</a>"> 
  
<!-- 这种加载方式可以在代码中通过@Value注解进行注入,  
You can assign the entire configuration to a class variable of type Properties, or you can take out one of them and assign it to a class variable of type String --> 
The <!-- <util:properties/> tag can only load one file. When multiple property files need to be loaded, multiple tags can be used --> 
<util:properties id="remoteSettings" location="file :/opt/demo/config/demo-remote.properties" />  
  
<!-- <util:properties/> The implementation class of the <util:properties/> tag is PropertiesFactoryBean, 
directly use the bean configuration of this class, and set its locations property to achieve one and the above The same purpose of loading multiple configuration files--> 
<bean id="settings"  
   class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
   <property name="locations"> 
  <list> 
    <value>file: /opt/rms/config/rms-mq.properties</value> 
    <value>file:/opt/rms/config/rms-env.properties</value> 
  </list> 
   </property> 
<  Annotation used in /bean>
</beans> 
Client class is as follows:
Java code Collection code
import org.springframework.beans.factory.annotation.Value; 
 
public class Client() { 
    @Value("#{remoteSettings['remote.ip']}") 
    private String ip; 
    @Value("#{remoteSettings['remote .port']}") 
    private String port; 
    @Value("#{remoteSettings['remote.serviceName']}") 
    private String service; 


Fourth, there is a class variable of type Properties in the Bean
Application scenario: when the Bean exists Class variables of type Properties need to be initialized by injection
1. Configuration method: We can use the configuration method in (3), just modify the following
Java code with annotations in the code Collection code
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.beans.factory.annotation.Autowired; 
 
public class Client() { 
    @Value("  #{remoteSettings}") 
    private Properties remoteSettings; 


2. Configuration method: You can also declare beans in xml and inject
Xml code Collection code
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www .springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans http: //www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
     
    <!-- You can use the following way to declare the FactoryBean of the Properties type to load the configuration file, which can only be used as Properties property injection , instead of getting the specific value --> 
    <bean id="remoteConfigs" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
        <property name="locations"  > 
            <list> 
                <value>file:/opt/demo/config/demo-remote.properties</value> 
            </list> 
        </property> 
    </bean> 
     
    <!-- Remote call client class --> 
    <bean id= "client" class="com.demo.remote.Client"> 
        <property name="properties" ref="remoteConfigs" /> 
    </bean> 
</beans>  The
code is as follows:
Java code Collection code
import org.springframework.beans .factory.annotation.Autowired; 
 
public class Client() { 
    //@Autowired can also use 
    private Properties remoteSettings; 
     
    //getter setter 


The above scenarios are particularly useful in project groups, and it is necessary to use the above various configuration methods flexibly.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327042632&siteId=291194637