1. First create a Maven project, the content of the Pom file is as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>myproject</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.6.RELEASE</version> </parent> <dependencies> <!-- add typical dependencies for a web application --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <build> <plugins> <!-- Spring Boot provides a Maven plugin for creating executable jars --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
The directory structure of the project is as follows:
1. Write Application
package com.zto.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * * * The first annotation used on our Example class is @RestController. This is called a stereotype annotation. It provides advice for people reading the code. * For Spring, this class plays a special role. In this example, our class is a web @Controller, so when processing incoming web requests, * Spring will ask him * */ @RestController @SpringBootApplication public class Application{ /** * @RequestMapping annotation provides routing information. It tells Spring that any request from the "/" path should be mapped to the home method. * The @RestController annotation tells Spring to render the result as a string and return it directly to the caller. */ @RequestMapping("/") String home(){ return "Hello World"; } public static void main(String[] args) throws Exception{ SpringApplication.run(Application.class, args); } }
2. Run the main method in the Application directly, and then enter http://localhost:8080/ in the browser
3. @SpringBootApplication annotation [The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAntoConfiguration and @ComponentScan with default properties. 】
4. @ConfigurationProperties annotation [Any beans annotated with @ConfigurationProperties will be automatically configured by Environment properties (application.properties, configuration in application.yml)]
package com.zto.demo.bean; import java.net.InetAddress; import javax.validation.constraints.NotNull; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix="connection") public class ConnectionSettings { private String username; /** * Spring Boot will try to verify the external configuration * NotNull check that the remoteAddress field cannot be empty, otherwise an error will be reported when starting the service */ //@NotNull private InetAddress remoteAddress; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public InetAddress getRemoteAddress() { return remoteAddress; } public void setRemoteAddress(InetAddress remoteAddress) { this.remoteAddress = remoteAddress; } @Override public String toString() { return "username :" + username + ", remote :"+remoteAddress; } }
5. Write application.properties and application.yml
person.name=gaoweigang
application.ymml file configuration
my: servers: - dev.bar.com - foo.bar.com mother: LiuJinJu first-name: GAO connection: username: admin #remoteAddress: 192.168.1.1
6. Write MyBean
package com.zto.demo.bean; import java.util.ArrayList; import java.util.List; import javax.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @ConfigurationProperties(prefix="my") public class MyBean { /** * Bundle the application.properties file into the jar to provide a reasonable default name property value */ @Value("${person.name}") private String name; /** * Test to generate integer random numbers */ @Value("${random.int}") private int age; /** * Use the Spring DataBinder tool to bind properties in the YAML file (this is what @ConfigurationProperties does), you need to determine the target bean * It must be initialized with a mutable value (because List is mutable, so there is no need to configure the corresponding setter method), * For example, the following code will bind the above properties */ private List<String> servers = new ArrayList<String>(); /** * Recommended, try not to use @Value() this way, this way is too cumbersome * Use the Spring DataBinder tool to bind properties in the YAML file (this is what @ConfigurationProperties does), you need to determine the target bean * There must be a setter method (because String is immutable, the setter method must be configured), for example, the following code will bind the above properties */ private String mother; /** * Loose binding (Relaxed binding): The fields in application.yml do not have to be exactly the same as the member variable names in the bean * Must have corresponding setter() method */ private String firstName; @Autowired private ConnectionSettings connection; @RequestMapping("/hello") public String hello(){ return "Hello "+name + "<br/>age :"+age + "<br/>servers: " + this.getServers() + "<br/>mother: "+ this.getMother()+ "<br/>first-name:"+firstName; } @RequestMapping("/connectionTest") public String connection(){ return connection.toString(); } public List<String> getServers() { return servers; } /* public void setServers(List<String> servers) { this.servers = servers; }*/ public String getMother() { return mother; } public void setMother(String mother) { this.mother = mother; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } }
6. Browser Authentication
①使用http://localhost:8080/hello
②使用http://localhost:8080/connectionTest
Proper explanation:
1. Starter POMs
Starter POMs are a convenient collection of dependency descriptors that can be included in an application. You can get a one-stop shop for all Spring and related technologies, while
No need to go through example code, copy-paste tons of dependency descriptors. For example, if you want to use Spring and JPA for database access, just in your project
Include the spring-boot-starter-data-jpa dependency and you're good to go.
The starters contain many of the dependencies you need to get your project up and running quickly, and provide a consistent, managed set of transitive dependencies.
What the names mean: All starters follow a similar naming pattern: spring-boot-starter-*, where * is a special type of application.
This naming structure is designed to help you find the starter you need. Maven integrated with many IDEs allows you to search for dependencies by name. For example, using the corresponding Eclipse or STS
plugins, you can simply hit ctrl-space in the POM editor and type "spring-boot-starter" for a full list.
2. Configuration class
Spring Boot advocates Java-based configuration. Although you can use an XML source to call SpringApplication.run(), we generally recommend that you use
@Configuration class as the main source. The class that generally defines the main method is also the main @Configuration
Automatic configuration
Spring Boot auto-configuration tries to auto-configure your Spring application based on the jar dependencies you add. For example, if HSQLDB exists on your classpath, and
You do not manually configure any data connection beans, then we will automatically configure an in-memory database.
You can opt for auto-configuration by adding the @EnbleAntoConfiguration or @SpringBootApplicaiton annotations to a @Configuration class.
Disable specific autoconfiguration
If you find that specific auto-configuration classes are applied that you don't want, you can disable them using the @EnableAutoConfiguration annotation exclusion attribute.
例如:@EnableAntoConfiguration(exclude={DataSourceAutoConfiguration.class})
3. Use the @SpringBootApplication annotation
Many Spring Boot developers always annotate their main classes with @Configuration, @EnbleAntoConfiguration and @ComponentScan.
Since these annotations are used together so frequently (especially if you follow the above best practices), Spring Boot provides a handy @SpringBootApplication
choose.
The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAntoConfiguration and @ComponentScan with default properties.
4. Run the application
One of the biggest benefits of packaging your application as a jar and using an embedded HTTP server is that you can run your application the same way you would otherwise. Debug Spring Boot
Application is also simple: you don't need any special IDE or extension
Web environment
A SpringApplication will try to create the correct type of ApplicationjContext for you. By default you use AnnotationConfigApplicationContext
or AnnotationConfigEmbeddedWebApplicationContext depending on whether you are developing a web application.
The algorithm used to determine a web environment is fairly simple (based on the existence of certain classes). If you need to override the default behavior, you can use setWebEnvironment(boolean webEnvironment).
You have full control over the type of ApplicationContext by calling setApplicationContextClass(...) .
Note: When using SpringApplication in JUnit tests, it is advisable to call setWebEnvironment(false)
5. Externalization configuration
Spring Boot allows you to externalize your configuration so you can use the same code in different environments. You can use properties file, YAML file,
Environment variables and command line arguments to externalize configuration. Using the @Value annotation, you can inject property values directly into your beans and use Spring's Environment
Abstract or bind to structured objects for access.
Spring Boot uses a very specific order of PropertySources to allow reasonable overriding of values, properties need to be considered in the following order:
1. Command line parameters
2. JNDI properties from java:comp/env
3. Java system properties (System.getProperties())
4. Operating system environment variables
5. Only the properties contained in random.* will generate a RandomValuePropertySource (that generates random numbers)
Application properties file
SpringApplication will load application.properties files from the following locations and add them to the Spring Environment:
1. A /config subdirectory in the current directory
2. Current directory
3. A /config package under a classpath
4.classpath root path (root)
This list is sorted by priority (higher positions in the list will override lower positions)
Note: You can use YAML ('*.yml') files instead of '.properties'
If you don't like to use application.properties as the configuration file name, you can switch to another name by specifying the spring.config.name environment property.
You can also use the spring.config.location environment property to refer to an explicit path (a comma-separated list of directory locations or file paths).
2. Specific Profile properties
In addition to the application.properties file, specific configuration properties can also be defined through the command convention application-{profile}.properties. specific
Profile properties are loaded from the same path as the standard application.properties, and specific profile files override the default configuration.
3. Property placeholders
When values in application.properties are used, they are filtered by the existing Environment, so you can reference previously defined values (eg, system properties).
app.name=MyApp
app.description=${app.name} is a Spring Boot application
Note: You can also use the corresponding trick to create 'short' variables for existing Spring Boot properties
4. Use YAML instead of Properties
YAML is a superset of JSON and a convenient format for defining hierarchical configuration data. Whenever you put the Snake YAML library on the classpath,
SpringApplicaiton classes automatically support YAML as a replacement for properties.
Note: If you use 'starter POMs', Spring-boot-starter will automatically provide Snake YAML.
5. Load YAML
The Spring framework provides two convenient classes for loading YAML documents, YamlPropertiesFactoryBean will load YAML as Properties,
YamlMapFactoryBean will load YAML as a Map.
Six. YAML shortcomings
YAML files cannot be loaded via the @PropertySource annotation. So, in this case, if you need to use the @PropertySource annotation to load the value,
Then use the Properties file.
seven.
Meaning of @PostConstruct annotation
Eight. @ConfigurationProperties check
Spring Boot will try to validate the external configuration