Several ways for Spring to load Properties configuration files

1: Load configuration file through context: Property placeholder tag

Add the following declaration to spring's configuration file

<context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties"/>

 

When referencing values, use $to reference the values you need
1. In datasource.xml

<!-- Configure data sources -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />

2. In java code

@Value("${targetVal}")  
private String targetVal; // Note: variables cannot be defined as static

 

2: Configuration file loading through util:properties tag

Add the following declaration to spring's configuration file

<util:properties id="jdbc" local-override="true" location="classpath:jdbc.properties"/>

Note that this approach requires the following declaration in the spring configuration file header

xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"

 

When referencing values, use the#
1. Use in xml

<property name="username" value="#{jdbc['jdbc.username']}" />
<property name="password" value="#{jdbc['jdbc.password']}" />

2. In java code

@Value(value="#{jdbc['targetVal']}")
private String targetVal;

 

3, Load configuration file with @ PropertySource annotation

Use the PropertySource annotation in the java class file:

@PropertySource(value={"classpath:jdbc.properties"})
public class ReadProperties {

    @Value(value="${jdbc.username}")
    private String username;

}

4, Read the configuration file through the PropertyPlaceholderConfigurer class

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>/WEB-INF/mail.properties</value>  
            <value>classpath:jdbc.properties</value>
        </list>
    </property>
</bean>

Value is the same as method 1

5: Load using PropertiesFactoryBean

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

Same value as method 2

The above is a common value taking method. The next chapter will introduce the common properties of context: Property placeholder

 

 

To: https://blog.csdn.net/Cool_Coding/article/details/90617687

Tags: JDBC Spring Java xml

Posted on Fri, 01 May 2020 20:02:46 -0700 by snog