Spring Comments (X) to load the configuration file

Often you need to modify some parameters in the project, or the latter is subject to change, and that we'd better put these parameters into the properties file, read the properties inside the configuration in the source code, so that the latter can only change properties file no need to modify the source code. The following discussion of two kinds of spring loading, xml-based and annotation-based loading.

1. Load the properties file by way xml

Spring to instantiate dataSource for example, first create a new conn.properties file in the src directory of the project, which is written on the top dataSource configuration:

dataSource=com.mchange.v2.c3p0.ComboPooledDataSource  
driverClass=com.mysql.jdbc.Driver  
jdbcUrl=jdbc:mysql://localhost:3306/shop 
username=root  
password=root 

Then only you need to make the following changes in the beans.xml:

 < Context: Property-placeholder LOCATION = "CLASSPATH: conn.Properties" /> <-! Load profile ->   
  
 ! <- com.mchange.v2.c3p0.ComboPooledDataSource class package c3p0-0.9.5.1.jar the package com.mchange.v2.c3p0 ->   
 < the bean ID = "the dataSource" class = "$ {} the dataSource" >  <-! these configurations Spring go looking at startup in conn.properties ->   
    < Property name = "driverClass" value = "$ {driverClass}"  />   
    < Property name = "the jdbcUrl" value = "$ {} the jdbcUrl" />  
    <property name="user" value="${user}" />  
    <property name="password" value="${password}" />  
 </bean>  

Tags can also use the following tags instead, more readable:

< The bean class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >   
    < Property name = "locations" >  <-! The PropertyPlaceholderConfigurer class has a property locations, an array is received, i.e., we can with the following a good number of properties file ->   
        < Array >   
            < value > the CLASSPATH: conf.properties </ value >   
        </ Array >   
    </ Property >   
</ bean >

2. Load the properties file by way of comment

First create a new resource file: public.properties

shop.url=http://magic/shop

The first configuration:

    <!-- 确保可在@Value中, 使用SeEL表达式获取资源属性 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />
    </bean>

    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:config/*.properties</value>
            </list>
        </property>
    </bean>

@Value configuration property values ​​acquired by the java code

    @Value("${shop.url}")
    private String url;

There is also a more concise way:

    < The bean ID = "prop" class = "org.springframework.beans.factory.config.PropertiesFactoryBean" >  
        < Property name = "of fileEncoding" value = "UTF-. 8" />  
        < Property name = "locations" > <! - - this is the class PropertiesFactoryBean, it also has a property locations, an array is received, as with the above   -> 
            < array >   
                < value > CLASSPATH: public.properties </ value >   
            </ array >   
        </ property >   
    </bean> 
    <!--Or -> 
    < context: Property-placeholder LOCATION = "the CLASSPATH: public.properties"  />   
    
    // Note that this method of expression must be set in order to be injected in, notes written on the set method to 
    private String url;   
    @value ( "prop.shop.url # {}")    
    // indicates to the Value @ beans.xml find file id = "prop" the bean, which is to read the configuration file by annotations properties manner, and then to the corresponding configuration file reading value corresponding to the value of key = shop.url   
    public void setUrl (String URL) {   
        this.token = URL;   
    }

3 to read the configuration file and @Value @PropertySource

@Component
@PropertySource(value = {"classpath:common.properties", "classpath:abc.properties"})
public class Configs {

    @Value("${connect.api.apiKeyId}")
    public String apiKeyId;

    @Value("${connect.api.secretApiKey}")
    public String secretApiKey;

    public String getApiKeyId() {
        return apiKeyId;
    }

    public String getSecretApiKey() {
        return secretApiKey;
    }
}

We come at specific analysis:

1, @ Component annotation Description This is a common bean, when the Component Scanning will be scanned into the Bean and injected into the vessel; where we can cite such Autowiring other. @Autowired this comment expressed the bean automatic assembly. such as:

@Controller
public class HomeController {

    @Autowired
    private Configs configs;
}

2, @ PropertySource annotation configuration file used to specify the path to be read so as to read the configuration file, the configuration file may specify a plurality of simultaneously;

3, @ Value ( "$ {connect.api.apiKeyId}") is used to read the value of the attribute key = connect.api.apiKeyId corresponding attribute and the value assigned to apiKeyId;

Often you need to modify some parameters in the project, or the latter is subject to change, and that we'd better put these parameters into the properties file, read the properties inside the configuration in the source code, so that the latter can only change properties file no need to modify the source code. The following discussion of two kinds of spring loading, xml-based and annotation-based loading.

1. Load the properties file by way xml

Spring to instantiate dataSource for example, first create a new conn.properties file in the src directory of the project, which is written on the top dataSource configuration:

dataSource=com.mchange.v2.c3p0.ComboPooledDataSource  
driverClass=com.mysql.jdbc.Driver  
jdbcUrl=jdbc:mysql://localhost:3306/shop 
username=root  
password=root  

Then only you need to make the following changes in the beans.xml:

 <context:property-placeholder location="classpath:conn.properties"/><!-- 加载配置文件 -->  
  
 <!-- com.mchange.v2.c3p0.ComboPooledDataSource类在c3p0-0.9.5.1.jar包的com.mchange.v2.c3p0包中 -->  
 <bean id="dataSource" class="${dataSource}"> <!-- 这些配置Spring在启动时会去conn.properties中找 -->  
    <property name="driverClass" value="${driverClass}" />  
    <property name="jdbcUrl" value="${jdbcUrl}" />  
    <property name="user" value="${user}" />  
    <property name="password" value="${password}" />  
 </bean>  

Tags can also use the following tags instead, more readable:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="locations"> <!-- PropertyPlaceholderConfigurer类中有个locations属性,接收的是一个数组,即我们可以在下面配好多个properties文件 -->  
        <array>  
            <value>classpath:conf.properties</value>  
        </array>  
    </property>  
</bean>

2. Load the properties file by way of comment

First create a new resource file: public.properties

shop.url=http://magic/shop

The first configuration:

    <!-- 确保可在@Value中, 使用SeEL表达式获取资源属性 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />
    </bean>

    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:config/*.properties</value>
            </list>
        </property>
    </bean>

@Value configuration property values ​​acquired by the java code

    @Value("${shop.url}")
    private String url;

There is also a more concise way:

    <bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
        <property name="fileEncoding" value="UTF-8"/> 
        <property name="locations"><!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样  
            <array>  
                <value>classpath:public.properties</value>  
            </array>  
        </property>  
    </bean> 
    <!--或者-->
    <context:property-placeholder location="classpath:public.properties" />  
    
    //注意,这种表达式要有set方法才能被注入进来,注解写在set方法上即可
    private String url;  
    @Value("#{prop.shop.url}")   
    //@Value表示去beans.xml文件中找id="prop"的bean,它是通过注解的方式读取properties配置文件的,然后去相应的配置文件中读取key=shop.url的对应的value值  
    public void setUrl(String url) {  
        this.token= url;  
    }

3 to read the configuration file and @Value @PropertySource

举个栗子:

@Component
@PropertySource(value = {"classpath:common.properties", "classpath:abc.properties"})
public class Configs {

    @Value("${connect.api.apiKeyId}")
    public String apiKeyId;

    @Value("${connect.api.secretApiKey}")
    public String secretApiKey;

    public String getApiKeyId() {
        return apiKeyId;
    }

    public String getSecretApiKey() {
        return secretApiKey;
    }
}

我们来具体分析下:

1、@Component注解说明这是一个普通的bean,在Component Scanning时会被扫描到并被注入到Bean容器中;我们可以在其它引用此类的地方进行自动装配。@Autowired这个注解表示对这个bean进行自动装配。 比如:

@Controller
public class HomeController {

    @Autowired
    private Configs configs;
}

2、@PropertySource注解用来指定要读取的配置文件的路径从而读取这些配置文件,可以同时指定多个配置文件;

3、@Value("${connect.api.apiKeyId}")用来读取属性key=connect.api.apiKeyId所对应的值并把值赋值给属性apiKeyId;

Guess you like

Origin www.cnblogs.com/deityjian/p/11445845.html