Spring Boot attribute configuration and custom attribute Configuration

Source: Internet
Author: User

Spring Boot attribute configuration and custom attribute Configuration

In the process of using spring boot, we can find that the project can complete the corresponding functions with only a few configurations, thanks to the modular configuration in spring boot, in pom. each Starter dependent on in xml has default configurations, which are sufficient for normal function development.

If you need to modify the default configuration, spring boot provides a simple method. You only need to add and modify the corresponding configuration in application. properties. (The default configuration of application. properties will be read when spring boot is started)

1. Modify the default configuration

Example 1: When spring boot is used to develop a web application, the default tomcat startup port is 8080. to modify the default port, add the following record in application. properties:

server.port=8888

Restart the project. The startup log shows that the Tomcat started on port (s): 8888 (http) Startup port is 8888, and access http: // localhost: 8888 in the browser is normal.

Example 2: configure the database connection information in spring boot Development (druid of com. alibaba is used here) and add the following records in application. properties:

druid.url=jdbc:mysql://192.168.0.20:3306/testdruid.driver-class=com.mysql.jdbc.Driverdruid.username=rootdruid.password=123456druid.initial-size=1druid.min-idle=1druid.max-active=20druid.test-on-borrow=true

The above two examples show that to modify the default configuration in the starter module, you only need to add the configuration to be modified in application. properties.

Appendix: All configuration items of application. properties. Click to view all configuration instructions of Spring Boot.

Ii. Custom property Configuration

In addition to modifying the default configuration in application. properties, we can also configure custom properties and load them in the object bean.

1. Add custom property configuration in application. properties

com.sam.name=samcom.sam.age=11com.sam.desc=magical sam

2. Write Bean classes and load attributes

The @ Component annotation must be added to the Sam class so that spring can scan the class at startup and add it to the spring container.

First: Use @ Value () supported by spring to load

Package com. sam. demo. conf; import org. springframework. beans. factory. annotation. value; import org. springframework. stereotype. component;/*** @ author sam * @ since #/7/15 */@ Componentpublic class Sam {// obtain the application. properties @ Value ("$ {com. sam. name} ") private String name; @ Value (" $ {com. sam. age} ") private int age; @ Value (" $ {com. sam. desc} ") private String desc; // getter & setter}

Type 2: Use @ ConfigurationProperties (prefix = "") to set the prefix. Annotations are not required for attributes.

package com.sam.demo.conf;import org.springframework.stereotype.Component;/** * @author sam * @since 2017/7/15 */@Component@ConfigurationProperties(prefix = "com.sam")public class Sam {  private String name;  private int age;  private String desc;  //getter & setter}

3. Inject and use the Bean Sam in the controller.

package com.sam.demo.controller;import com.sam.demo.conf.Sam;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;/** * @author sam * @since 2017/7/14 */@RestControllerpublic class IndexController {  @Autowired  private Sam sam;  @RequestMapping("/index")  public String index() {    System.out.println(sam.getName() + " " + sam.getAge() + " " + sam.getDesc());    return "index";  }}

Browser access: http: // localhost: 8080/index. The console prints the sam content normally.

Iii. Detailed description of application. properties attribute Configuration

1. Use of parameter reference and random Number Method

In application. properties, you can directly reference the values of other properties through $ {}, as shown below:

com.sam.name=samcom.sam.age=11com.sam.desc=${name} is ${age} years old. 

To obtain a random number in application. properties, run $ {random} as follows:

# Obtain the random string com. sam. randomValue =$ {random. value} # obtain a random string: $ {random. value} # obtain random int :$ {random.int} # obtain a random number of less than 10: $ {random.int (10)} # obtain a random number of 10-20: $ {random.int [10, 20]} # obtain random long :$ {random. long} # obtain random uuid: $ {random. uuid}

2. Multi-Environment Configuration

In actual development, there may be different environments, including the development environment, test environment, and generation environment. Configuration may vary in each environment, such as database information, port configuration, and local path configuration.

If you need to modify application. properties every time you switch between different environments, the operation is very cumbersome. Multi-Environment configuration is provided in spring boot, making it easy to switch the environment.

Create three files in the same directory of application. properties:

Application-dev.properties // configuration file for Development Environment application-test.properties // configuration file for test environment application-prod.properties // configuration file for production environment

The above three files correspond to the development, testing, and production configuration content respectively. Next, we will discuss how to selectively reference these configurations.

Add the following in application. properties:

Spring. profiles. active = dev # reference the test configuration file # spring. profiles. active = test # reference the production configuration file # spring. profiles. active = prod

Start the application after adding spring. profiles. active = dev. The configuration information of dev is referenced.

It can be seen that the above three configuration files comply with the application-{profile}. properties format, and dev in spring. profiles. active = dev added in application. properties is the profile in the above configuration file. Switch Based on the specific environment.

When you run the jar package to start the application, you can specify the corresponding configuration.

java -jar demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

Appendix: configuration method and priority
The priority of these methods is as follows:
A. Command Line Parameters
B. JNDI attributes from java: comp/env
C. Java System attributes (System. getProperties ())
D. Operating System Environment Variables
E. RandomValuePropertySource: random. * Attribute Value
F. jar External application-{profile}. properties or application. yml (with spring. profile) configuration file
Application-{profile}. properties or application. yml (with spring. profile) configuration file in g. jar
Application. properties or application. yml (without spring. profile) configuration file outside h.jar
I. jar internal application. properties or application. yml (without spring. profile) configuration file
J. @ PropertySource on the Configuration annotation class
K. The default attribute specified through SpringApplication. setDefaultProperties

Note: It may be insecure to specify a parameter in the jar package such as the command line parameter to start the application. We can disable this method to start the application as follows:

springApplication.setAddCommandLineProperties(false);

Package com. sam. demo; import org. springframework. boot. springApplication; import org. springframework. boot. autoconfigure. springBootApplication; @ SpringBootApplicationpublic class DemoApplication {public static void main (String [] args) {// SpringApplication. run (DemoApplication. class, args); SpringApplication springApplication = new SpringApplication (DemoApplication. class); // disable the command line Setting Parameter springApplication. setAddCommandLineProperties (false); springApplication. run (args );}}

Supplement:

In spring boot, besides application. properties, application. yml can be configured as follows:

Create application. yml instead of application. properties

server: port: 9999com: sam:  name: sam  age: 11  desc: magical sam

Note: There are spaces in port: 9999. For the yml syntax, see: yml configuration file usage.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.