Spring @Value simplifies reading of configuration files

Spring @Value simplifies reading of configuration files

 

1. Configure the properties file in the applicationContext.xml file

<bean id="appProperty"

    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

    <property name="locations">

        <array>

            <value>classpath:app.properties</value>

        </array>

    </property>

 

</bean>

 

or simple operation

<context:property-placeholder location="classpath*:*.properties" />

 

2. Use the @value annotation in the bean to get the value of the configuration file

import org.springframework.beans.factory.annotation.Value;

@Value("${test.string:null}")

 

private String testStr;

 

 

 

Import a list from properties file

@Value("#{'${server.name:baidu,google,yahoo}'.split(',')}")

 

private List<String> servers;

 

Import a map from properties file

application.properties:

property.map={first:value, second:value}

then in Java code you can:

 

@Value("#{${property.map}}")

Map<String, String> map;

 

else

@Value("#{'${dmin.details.fields}'.split(',')}")

private List<String> fields;

 

private Map<String, String> fieldsMap;

 

@PostConstruct

public void init() {

    fieldsMap = new HashMap<String, String>();

    if (fields != null && fields.size() != 0) {

        for (String field : fields) {

            String[] splittedField = field.split(",");

            fieldsMap.put(splittedField[0], splittedField[1]);

        }

    }

}

 

 

 

 

Guess you like

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