The ubiquitous Properties in Spring

Source: Internet
Author: User

Transferred from: https://javadoop.com/post/spring-properties?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source= Toutiao.io

The ubiquitous Properties in Spring

Update Time: 2018-01-03

Developers who do not understand the Properties in Spring may feel a bit messy, mainly because there are many ways to configure them, and there are many ways to use them.

This article is not a principle analysis, source code analysis article, just hope to help readers better understand and use Spring Properties.

Use of Properties

Readers of this article have used spring, first of all to see how the Properties are used, Spring is commonly used in the following ways:

1. Using in the XML configuration file

That is, automatically replace ${} the value inside.

<Bean Id="XXX" Class="Com.javadoop.Xxx"> <property Name="url" value="${javadoop.jdbc.url}" / ></beans>             
2. Using @Value Injection
@Value("${javadoop.jdbc.url}")private String url;
3. Get through environment

There is a need to pay attention to this method. Not all configuration methods are supported through the environment interface to obtain property values, pro-test only when using annotations @PropertySource can be used, otherwise you will get null, as to how to configure, the following will be said immediately.

@Autowiredprivate Environment env;public String getUrl() { return env.getProperty("javadoop.jdbc.url");}

If it is a Spring Boot application.properties registered, it is also possible.

Properties Configuration

We said before how to use the Properties of our configuration, then how to configure it? Spring provides many ways to configure it.

1. Configuring with XML

The following is the most commonly used configuration, many projects are written in this way:

<context:property-placeholder location="classpath:sys.properties" />
2. Through @PropertySource configuration

The preceding XML configuration is very common, but if you have an impulse to destroy all of the XML configuration files, you should use the following method:

@PropertySource("classpath:sys.properties")@Configurationpublic class JavaDoopConfig {}

Note that @PropertySource must be used here with @Configuration, specifically not to expand.

3. Propertyplaceholderconfigurer

If the reader has seen this, it is not surprising that it is often used before Spring 3.1:

<Bean Class="Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><Property Name="Locations"><List><Value>classpath:sys.properties</Value></List></Property><property< Span class= "Hljs-tag" > name = "IgnoreUnresolvablePla Ceholders " value< Span class= "Hljs-tag" >= "true" /> <!--Here you can configure some properties--></bean>             

Of course, we can also use the corresponding Java configuration version:

  @Bean  public Propertyplaceholderconfigurer  Propertiess ()  {Propertyplaceholderconfigurer PPC = new propertyplaceholderconfigurer (); resource[] Resources = new classpathresource[]{new Classpathresource ( "sys.properties")}; Ppc.setlocations (resources); Ppc.setignoreunresolvableplaceholders (true); return PPC;}            
4. Propertysourcesplaceholderconfigurer

By the time Spring 3.1 was introduced, Propertysourcesplaceholderconfigurer, a new class, was noticed and the previous propertyplaceholderconfigurer had one more name on it. Sources, the owning package is not the same, it is in the Spring-context package.

There's no difference in configuration:

<Bean Class="Org.springframework.context.support.PropertySourcesPlaceholderConfigurer"><Property Name="Locations"><List><Value>classpath:sys.properties</Value></List></Property><property< Span class= "Hljs-tag" > name = "IgnoreUnresolvablePla Ceholders " value< Span class= "Hljs-tag" >= "true" /> <!--Here you can configure some properties--></bean>             

The

also comes with a Java configuration version:

@Beanpublic propertysourcesplaceholderconfigurer Properties() { Propertysourcesplaceholderconfigurer PSPC = new Propertysourcesplaceholderconfigurer (); resource[] Resources = new classpathresource[]{new Classpathresource ("sys.properties")}; Pspc.setlocations (resources); Pspc.setignoreunresolvableplaceholders (true); return PSPC;}           
Spring Boot Related

Spring Boot is really a good thing, and it's great to be out of the box. Here is a brief description of the relevant content.

Quickly generate a Spring Boot project: https://start.spring.io/

Application.properties

Each of our projects has a application.properties file by default, which does not need to be registered as previously stated, and Spring Boot will automatically register it for us.

Of course, you may want to change a name is also possible, at the start of the time to specify your file name can be:

java -Dspring.config.location=classpath:sys.properties -jar app.jar
Application-{env}.properties

In order to specify different configurations for different environments, we will use this.

For example, the database connection information for the test environment and the production environment is different.

So, on the basis of application.properties, we also need to create new application-dev.properties and Application-prd.properties is used to configure environment-related information and then to specify the environment when it is started.

java -Dspring.profiles.active=prd -jar app.jar

As a result, the configuration in Application.properties and application-prd.properties two files is registered, if there is a duplicate key,application-prd.properties Higher priority in the file.

@ConfigurationProperties

This annotation is only in Spring Boot.

Even if you do not use this annotation, you will probably see this in open source projects, here is a brief introduction.

Come up with an example that is intuitive. As previously stated, fill in the following information in the configuration file, you can choose to write application.properties can also use the method described in the first section.

javadoop.database.url=jdbc:mysql:javadoop.database.username=adminjavadoop.database.password=admin123456

Java files:

@Configuration@ConfigurationProperties(prefix = "javadoop.database")public class DataBase { String url; String username; String password; // getters and setters}

In this way, a bean of type DataBase is automatically registered in the container of Spring, and the properties are set well.

Dynamically modifying property values during startup

I don't think I need a lot of introductions, and the Spring Boot should basically know.

The property configuration has a overwrite order, that is, when the same key appears, the value of where to prevail.

Startup parameters > Application-{env}.properties > Application.properties

Startup parameters Dynamic Setting properties:

java -Djavadoop.database.password=admin4321 -jar app.jar

In addition, you can also use the system environment variables to set properties, you can specify random numbers and so on, it is very flexible, but no use, not introduced.

Summarize

If you want to know more about spring's Properties, you need to understand spring's environment interface-related source code. Suggest interested readers to turn over the source code to see

(End of full text)

The ubiquitous Properties in Spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.