http://blog.javachen.com/2015/03/13/how-to-run-spring-boot-application.html html
http://blog.javachen.com/2015/03/13/some-spring-boot-features.htmljava
http://blog.javachen.com/2016/02/19/spring-boot-auto-configuration.html mysql
在上篇文章如何运行Spring Boot应用中,已经熟悉了如何经过maven或者gradle建立一个Spring Boot应用,这篇文章主要学习Spring Boot的自动配置,包括注解的使用以及一些配置约束等等。git
关于Spring Boot的特性介绍,能够参考Spring Boot特性。github
在Spring Boot应用中,咱们一般将主应用类放置于应用的根包中,例如,com.javachen.example
。主应用类有main方法,而且使用了@EnableAutoConfiguration
注解,并暗地里定义了一个基础的包路径,Spring Boot会在该包路径来搜索类。例如,若是你正在编写一个JPA应用,被@EnableAutoConfiguration
注解的类所在包将被用来搜索带有@Entity
注解的实体类。web
在主应用类上指定@ComponentScan
,一样也隐式的指定了扫描时basePackage的路径。算法
如何运行Spring Boot应用中Application.java类声明了main方法,还使用了@EnableAutoConfiguration
注解。spring
@RestController @EnableAutoConfiguration public class Application { @RequestMapping("/") String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }pasting
说明:sql
@RestController
和@RequestMapping
注解是Spring MVC注解,它们不是Spring Boot的特定部分,具体查看Spring参考文档的MVC章节。@EnableAutoConfiguration
这个注解告诉Spring Boot根据添加的jar依赖猜想你想如何配置Spring。因为spring-boot-starter-web添加了Tomcat和Spring MVC,因此auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。在该类上也能够使用@Configuration
注解,用来对spring boot进行配置,固然,你也能够使用一个XML源来调用SpringApplication.run()
进行配置。数据库
标有@Configuration
注解的类为配置类。你不须要将全部的@Configuration
放进一个单独的类。@Import
注解能够用来导入其余配置类。另外,你也能够使用@ComponentScan
注解自动收集全部的Spring组件,包括@Configuration
类。
若是你须要使用基于XML的配置,你能够在注有@Configuration
的类上使用附加的@ImportResource
注解加载XML配置文件。
你能够经过将@EnableAutoConfiguration
或@SpringBootApplication
注解添加到一个@Configuration
类上来选择自动配置。自动配置的意思是Spring Boot尝试根据你添加的jar依赖自动配置你的Spring应用。
若是须要找出当前应用了哪些自动配置及应用的缘由,你能够使用--debug
开关启动应用,这将会记录一个自动配置的报告并输出到控制台。
若是发现应用了你不想要的特定自动配置类,你能够使用@EnableAutoConfiguration
注解的排除属性来禁用它们。
import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; import org.springframework.context.annotation.*; @Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration { }
总结,上面提到了几个注解,用途分别以下:
@Configuration
。标注一个类为配置类。@EnableAutoConfiguration
。开启自动配置。@SpringBootApplication
。等价于以默认属性使用@Configuration
,@EnableAutoConfiguration
和@ComponentScan
。若是启动类在根包下面,则你能够在该类上添加@ComponentScan
注解而不须要添加任何参数,Spring Boot会在根包下面搜索注有@Component
, @Service
,@Repository
, @Controller
注解的全部类,并将他们注册为Spring Beans,不然,你须要在@ComponentScan
注解上定义basePackages或者其余属性。
这样Application.java能够定义为:
package com.javachen.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @Configuration @ComponentScan @EnableAutoConfiguration public class Application { @RequestMapping("/") String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
或者:
package com.javachen.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class Application { @RequestMapping("/") String home() { return "Hello World!"; } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
启动类能够实现CommandLineRunner接口,经过run方法处理main方法传入的参数,而且你可以使用@Value
注解将命令行参数传入的值或者properties资源文件中定义的值注入到程序中。例如,建立一个HelloWorldService类:
package com.javachen.example.service; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class HelloWorldService { @Value("${name:World}") private String name; public String getMessage() { return "Hello " + this.name; } }
并添加资源文件application.properties:
name: JavaChen
修改Application类为以下:
package com.javachen.example; import com.javachen.example.service.HelloWorldService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class Application implements CommandLineRunner { @Autowired private HelloWorldService helloWorldService; @RequestMapping("/") String home() { return "Hello World!"; } @Override public void run(String... args) { System.out.println(this.helloWorldService.getMessage()); if (args.length > 0 && args[0].equals("exitcode")) { throw new ExitException(); } } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } }
运行该类的main方法,则默认会输出:
Hello JavaChen
再次运行main方法,并传入参数--name=whatever
,则会输出:
Hello whatever
若是一些CommandLineRunner beans被定义必须以特定的次序调用,你能够额外实现org.springframework.core.Ordered
接口或使用@Order
注解。
利用command-line runner的这个特性,再配合依赖注入,能够在应用程序启动时后首先引入一些依赖bean,例如data source、rpc服务或者其余模块等等,这些对象的初始化能够放在run方法中。不过,须要注意的是,在run方法中执行初始化动做的时候一旦遇到任何异常,都会使得应用程序中止运行,所以最好利用try/catch语句处理可能遇到的异常。
每一个SpringApplication在退出时为了确保ApplicationContext被优雅的关闭,将会注册一个JVM的shutdown钩子。全部标准的Spring生命周期回调(好比,DisposableBean接口或@PreDestroy注解)都能使用。
此外,若是beans想在应用结束时返回一个特定的退出码,能够实现org.springframework.boot.ExitCodeGenerator
接口,例如上面例子中的ExitException异常类:
package com.javachen.example; import org.springframework.boot.ExitCodeGenerator; public class ExitException extends RuntimeException implements ExitCodeGenerator { @Override public int getExitCode() { return 10; } }
在启动类上使用@EnableAutoConfiguration
注解,就会开启自动配置,简单点说就是它会根据定义在classpath下的类,自动的给你生成一些Bean,并加载到Spring的Context中。
它的神秘之处,不在于它能作什么,而在于它会生成什么样的Bean对于开发人员是不可预知(或者说不容易预知)。
例如,上面例子中引入了对spring-boot-starter-web的依赖,则会开启Spring MVC自动配置,观察启动日志,能够发现应用启动了tomcat和spring mvc。
Spring Boot为Spring MVC提供适用于多数应用的自动配置功能。在Spring默认基础上,自动配置添加了如下特性:
若是想全面控制Spring MVC,你能够添加本身的@Configuration,并使用@EnableWebMvc
对其注解。若是想保留Spring Boot MVC的特性,并只是添加其余的MVC配置(拦截器,formatters,视图控制器等),你能够添加本身的WebMvcConfigurerAdapter类型的@Bean
(不使用@EnableWebMvc
注解)。
再举个例子:要开发一个基于Spring JPA的应用,会涉及到下面三个Bean的配置,DataSource,EntityManagerFactory,PlatformTransactionManager。
@Configuration @EnableJpaRepositories @EnableTransactionManagement public class Application { @Bean public DataSource dataSource() { ... } @Bean public EntityManagerFactory entityManagerFactory() { .. factory.setDataSource(dataSource()); return factory.getObject(); } @Bean public PlatformTransactionManager transactionManager() { JpaTransactionManager txManager = new JpaTransactionManager(); txManager.setEntityManagerFactory(entityManagerFactory()); return txManager; } }
说明:
@EnableJpaRepositories
会查找知足做为Repository条件(继承父类或者使用注解)的类。@EnableTransactionManagement
的做用:Enables Spring’s annotation-driven transaction management capability, similar to the support found in Spring’s <tx:*> XML namespace。可是,若是你使用了@EnableAutoConfiguration
,那么上面三个Bean,你都不须要配置。在classpath下面只引入了MySQL的驱动和SpringJpa。
compile 'mysql:mysql-connector-java:5.1.18' compile 'org.springframework.boot:spring-boot-starter-data-jpa'
在生产环境中,数据库链接能够使用DataSource池进行自动配置。下面是选取一个特定实现的算法:
若是你使用spring-boot-starter-jdbc或spring-boot-starter-data-jpa,你将会自动获取对tomcat-jdbc的依赖。
DataSource配置经过外部配置文件的spring.datasource.*
属性控制。示例中,你可能会在application.properties
中声明下面的片断:
spring.datasource.url=jdbc:mysql://localhost/test spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.jdbc.Driver
其余可选的配置能够查看DataSourceProperties。同时注意你能够经过spring.datasource.*
配置任何DataSource实现相关的特定属性:具体参考你使用的链接池实现的文档。
既然Spring Boot可以从大多数数据库的url上推断出driver-class-name,那么你就不须要再指定它了。对于一个将要建立的DataSource链接池,咱们须要可以验证Driver是否可用,因此咱们会在作任何事情以前检查它。好比,若是你设置
spring.datasource.driverClassName=com.mysql.jdbc.Driver
,而后这个类就会被加载。
Spring的JdbcTemplate和NamedParameterJdbcTemplate类是被自动配置的,你能够在本身的beans中经过@Autowire
直接注入它们。
若是数据源是jndi,则定义:
spring.datasource.jndi-name=java:jboss/datasources/customers
若是不想使用注解进行配置,则能够使用xml配置文件,修改main方法以下:
public static void main(String[] args) throws Exception { SpringApplication.run("classpath:/META-INF/application-context.xml", args); }
META-INF/application-context.xml文件以下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <context:property-placeholder/> <bean id="helloService" class="com.javachen.example.service.HelloWorldService"/> <bean id="application" class="com.javachen.example.Application"/> </beans>