1.首先创建一个Maven项目,Pom文件的内容如下:
<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提供了一个用于创建可执行jars的Maven插件 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
项目的目录结构如下:
1.编写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;
/**
*
*
* 我们的Example类上使用的第一个注解是@RestController。这被称为一个构造型注解。它为阅读代码的人们提供建议。
* 对于Spring,该类扮演了一个特殊角色。在本示例中,我们的类是一个web @Controller,所以当处理进来的web请求时,
* Spring会询问他
*
*/
@RestController
@SpringBootApplication
public class Application{
/**
* @RequestMapping注解提供路由信息。它告诉Spring任何来自"/"路径的请求都应该被映射到home方法。
* @RestController注解告诉Spring以字符串的形式渲染结果,并直接返回给调用者 。
*/
@RequestMapping("/")
String home(){
return "Hello World";
}
public static void main(String[] args) throws Exception{
SpringApplication.run(Application.class, args);
}
}
2.直接运行Application中的main方法,然后在浏览器中输入http://localhost:8080/
3.@SpringBootApplication注解【该@SpringBootApplication注解等价于以默认属性使用@Configuration, @EnableAntoConfiguration 和 @ComponentScan。】
4.@ConfigurationProperties注解【任何被@ConfigurationProperties注解的beans将自动被Environment属性(application.properties,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将尝试校验外部的配置
* NotNull校验remoteAddress字段不能为空,否则启动服务将会报错
*/
//@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.编写application.properties以及application.yml
person.name=gaoweigang
application.ymml文件配置
my: servers: - dev.bar.com - foo.bar.com mother: LiuJinJu first-name: GAO connection: username: admin #remoteAddress: 192.168.1.1
6.编写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 {
/**
* 将application.properties文件捆绑到jar内,用来提供一个合理的默认name属性值
*/
@Value("${person.name}")
private String name;
/**
* 测试生成整形随机数
*/
@Value("${random.int}")
private int age;
/**
* 使用Spring DataBinder工具绑定YAML文件中的属性(这是@ConfigurationProperties做的事),你需要确定目标bean中
* 必须要有可变的值初始化它(因为List是可变的,所以就不用配置相应的setter方法),
* 比如,下面的代码将绑定上面的属性
*/
private List<String> servers = new ArrayList<String>();
/**
* 推荐使用,尽量不要使用@Value()这种方式,这种方式太笨重了
* 使用Spring DataBinder工具绑定YAML文件中的属性(这是@ConfigurationProperties做的事),你需要确定目标bean中
* 必须要有setter方法(因为String是不可变的,所以必须配置setter方法),比如,下面的代码将绑定上面的属性
*/
private String mother;
/**
* 松散绑定(Relaxed binding):application.yml中的字段不必和bean中的成员变量名完全一致
* 必须要有相应setter()方法
*/
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.浏览器验证
①使用http://localhost:8080/hello
②使用http://localhost:8080/connectionTest
适当的解释:
一.Starter POMs
Starter POMs是可以包含到应用中的一个方便的依赖关系描述符集合。你可以获取所有Spring及相关技术的一站式服务,而
不需要翻阅示例代码,拷贝粘贴大量的依赖描述符。例如,如果你想使用Spring和JPA进行数据库访问,只需要在你的项目中
包含spring-boot-starter-data-jpa依赖,然后你就可以开始了。
该starters包含很多你搭建项目,快速运行所需要的依赖,并提供一致的,管理的传递依赖集。
名字有什么含义:所有的starters遵循一个相似的命名模式:spring-boot-starter-*,在这里*是一种特殊类型的应用程序。
该命名结构旨在帮你找到需要的starter。很多IDEs集成的Maven允许你通过名称搜索依赖。例如,使用相应的Eclipse或STS
插件,你可以简单地在POM编辑器中点击ctrl-space,然后输入“spring-boot-starter"可以获取一个完整列表。
二.配置类
Spring Boot提倡基于Java的配置。尽管你可以使用一个XML源来调用SpringApplication.run(),我们通常建议你使用
@Configuration类作为主要源。一般定义main方法的类也是主要@Configuration
自动配置
Spring Boot自动配置尝试根据你添加的jar依赖自动配置你的Spring应用。例如,如果你的classpath下存在HSQLDB,并且
你没有手动配置任何数据连接beans,那么我们将自动配置一个内存型数据库。
你可以通过将@EnbleAntoConfiguration或者@SpringBootApplicaiton注解添加到一个@Configuration类上来选择自动配置。
禁用特定的自动配置
如果发现应用了你不想要的特定自动配置类,你可以使用@EnableAutoConfiguration注解排除属性来禁用它们。
例如:@EnableAntoConfiguration(exclude={DataSourceAutoConfiguration.class})
三.使用@SpringBootApplication注解
很多Spring Boot开发者总是使用@Configuration, @EnbleAntoConfiguration和@ComponentScan 注解他们的main类。
由于这些注解被如此频繁地一块使用(特别是你遵循以上最佳实践时),Spring Boot提供一个方便的@SpringBootApplication
选择。
该@SpringBootApplication注解等价于以默认属性使用@Configuration, @EnableAntoConfiguration 和 @ComponentScan。
四.运行应用程序
将应用打包成jar并使用一个内嵌HTTP服务器的一个最大好处是,你可以像其他方式那样运行你的应用程序。调试Spring Boot
应用也很简单:你不需要任何特殊IDE或扩展
Web环境
一个SpringApplication将尝试为你创建正确类型的ApplicationjContext。在默认你情况下,使用AnnotationConfigApplicationContext
或AnnotationConfigEmbeddedWebApplicationContext取决于你正在开发的是否是web应用。
用于确定一个web环境的算法相当简单(基于是否存在某些类)。如果需要覆盖默认的行为,你可以使用setWebEnvironment(boolean webEnvironment)。
通过调用setApplicationContextClass(...),你可以完全控制ApplicationContext的类型。
注:当JUnit测试里使用SpringApplication,调用setWebEnvironment(false)是可取的
五.外化配置
Spring Boot允许外化你的配置,这样你能够在不同 的环境下使用相同的代码。你可以使用properties文件,YAML文件,
环境变量和命令行参数来外化配置。使用@Value注解,可以直接将属性值注入到你的beans中,并通过Spring的Environment
抽象或绑定到结构化对象来访问。
Spring Boot使用一个非常特别的PropertySource次序来允许对值进行合理的覆盖,需要以下面的次序考虑属性:
1.命令行参数
2.来自于java:comp/env的JNDI属性
3.Java系统属性(System.getProperties())
4.操作系统环境变量
5.只有在random.*里包含的属性会产生一个RandomValuePropertySource(生成随机数的)
Application属性文件
SpringApplication将从以下位置加载application.properties文件,并把它们添加到Spring Environment中:
1.当前目录下的一个/config子目录
2.当前目录
3.一个classpath下的/config包
4.classpath根路径(root)
这个列表是按优先级排序的(列表中的位置高的将覆盖位置低的)
注:你可以使用YAML('*.yml')文件替代'.properties'
如果不喜欢将application.properties作为配置文件名,你可以通过指定spring.config.name环境属性来切换其他的名称。
你也可以使用spring.config.location环境属性来引用一个明确的路径(目录位置或文件路径列表以逗号分隔)。
二.特定的Profile属性
除了application.properties文件,特定配置属性也能通过命令惯例application-{profile}.properties来定义。特定
Profile属性从跟标准application.properties相同的路径加载,并且特定profile文件会覆盖默认的配置。
三.属性占位符
当application.properties里的值被使用时,它们会被存在的Environment过滤,所以你能够引用先前定义的值(比如,系统属性)。
app.name=MyApp
app.description=${app.name} is a Spring Boot application
注:你也能使用相应的技巧为存在的Spring Boot属性创建'短'变量
四.使用YAML代替Properties
YAML是JSON的一个超集,也是一种方便的定义层次配置数据的格式。无论你何时将Snake YAML库放到classpath下,
SpringApplicaiton类都会自动支持YAML作为properties的替换。
注:如果你使用'starter POMs', Spring-boot-starter会自动提供Snake YAML。
五.加载YAML
Spring框架提供两个便利的类用于加载YAML文档,YamlPropertiesFactoryBean会将YAML作为Properties来加载,
YamlMapFactoryBean会将YAML作为Map来加载。
六.YAML缺点
YAML文件不能通过@PropertySource注解加载。所以,在这种情况下,如果需要使用@PropertySource注解的方式加载值,
那就要使用Properties文件。
七.
@PostConstruct 注解的含义
八.@ConfigurationProperties校验
Spring Boot将尝试校验外部的配置