在这一部分,咱们主要了解如下3个问题:css
SpringBoot是Spring项目中的一个子工程,与咱们所熟知的Spring-framework 同属于spring的产品:html
咱们能够看到下面的一段介绍:java
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".mysql
We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.git
翻译一下:程序员
Spring Boot你只须要“run”就能够很是轻易的构建独立的、生产级别的spring应用。github
咱们为spring平台和第三方依赖库提供了一种固定化的使用方式,使你能很是轻松的开始开发你的应用程序。大部分Spring Boot应用只须要不多的配置。web
其实人们把Spring Boot称为搭建程序的脚手架
。其最主要做用就是帮咱们快速的构建庞大的spring项目,而且尽量的减小一切xml配置,作到开箱即用,迅速上手,让咱们关注于业务而非配置。redis
咱们可使用SpringBoot建立java应用,并使用java –jar 启动它,就能获得一个生产级别的web工程。spring
java一直被人诟病的一点就是臃肿、麻烦。当咱们还在辛苦的搭建项目时,可能Python程序员已经把功能写好了,究其缘由主要是两点:
复杂的配置
项目各类配置实际上是开发时的损耗, 由于在思考 Spring 特性配置和解决业务问题之间须要进行思惟切换,因此写配置挤占了写应用程序逻辑的时间。
混乱的依赖管理
项目的依赖管理也是件吃力不讨好的事情。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库的哪一个版本和其余库不会有冲突,这也是件棘手的问题。而且,依赖管理也是一种损耗,添加依赖不是写应用程序代码。一旦选错了依赖的版本,随之而来的不兼容问题毫无疑问会是生产力杀手。
而SpringBoot让这一切成为过去!
Spring Boot 主要特征是:
总之,Spring Boot为全部 Spring 的开发者提供一个开箱即用的、很是快速的、普遍接受的入门体验
更多细节,你们能够到官网查看。
接下来,咱们就来利用SpringBoot搭建一个web工程,体会一下SpringBoot的魅力所在!
环境要求:
咱们先新建一个空的demo工程,建立moduel并填写坐标信息。
建立完成后的目录结构:
看到这里不少同窗会有疑惑,前面说传统开发的问题之一就是依赖管理混乱,怎么这里咱们还须要管理依赖呢?难道SpringBoot不帮咱们管理吗?
别着急,如今咱们的项目与SpringBoot尚未什么关联。SpringBoot提供了一个名为spring-boot-starter-parent的工程,里面已经对各类经常使用依赖(并不是所有)的版本进行了管理,咱们的项目须要以这个项目为父工程,这样咱们就不用操心依赖的版本问题了,须要什么依赖,直接引入坐标便可!
<?xml version="1.0" encoding="UTF-8"?> <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>cn.itcast.springboot</groupId> <artifactId>itcast-springboot</artifactId> <version>1.0-SNAPSHOT</version> <!-- 全部的springboot的工程都以spring父工程为父工程 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
代码:
@RestController @EnableAutoConfiguration public class HelloController { @GetMapping("show") public String test(){ return "hello Spring Boot!"; } public static void main(String[] args) { SpringApplication.run(HelloController.class, args); } }
bingo!访问成功!
入门工程中:pom.xml里引入了启动器的概念以@EnableAutoConfiguration注解。
为了让SpringBoot帮咱们完成各类自动配置,咱们必须引入SpringBoot提供的自动配置依赖,咱们称为启动器
。spring-boot-starter-parent工程将依赖关系声明为一个或者多个启动器,咱们能够根据项目需求引入相应的启动器,由于咱们是web项目,这里咱们引入web启动器:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
须要注意的是,咱们并无在这里指定版本信息。由于SpringBoot的父工程已经对版本进行了管理了。
这个时候,咱们会发现项目中多出了大量的依赖:
这些都是SpringBoot根据spring-boot-starter-web这个依赖自动引入的,并且全部的版本都已经管理好,不会出现冲突。
关于这个注解,官网上有一段说明:
Enable auto-configuration of the Spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined.
简单翻译如下:
开启spring应用程序的自动配置,SpringBoot基于你所添加的依赖和你本身定义的bean,试图去猜想并配置你想要的配置。好比咱们引入了
spring-boot-starter-web
,而这个启动器中帮咱们添加了tomcat
、SpringMVC
的依赖。此时自动配置就知道你是要开发一个web应用,因此就帮你完成了web及SpringMVC的默认配置了!
总结,SpringBoot内部对大量的第三方库或Spring内部库进行了默认配置,这些配置是否生效,取决于咱们是否引入了对应库所需的依赖,若是有那么默认配置就会生效。
因此,咱们使用SpringBoot构建一个项目,只须要引入所需依赖,配置就能够交给SpringBoot处理了。
如今工程中只有一个Controller,能够这么玩;那么若是有多个Controller,怎么办呢?
添加Hello2Controller
代码:
@RestController public class Hello2Controller { @GetMapping("show2") public String test(){ return "hello Spring Boot2!"; } }
启动从新启动,访问show2测试,失败:
难道要在每个Controller中都添加一个main方法和@EnableAutoConfiguration注解,这样启动一个springboot程序也太麻烦了。也没法同时启动多个Controller,由于每一个main方法都监听8080端口。因此,一个springboot程序应该只有一个springboot的main方法。
因此,springboot程序引入了一个全局的引导类。
一般请求下,咱们在一个springboot工程中都会在基包下建立一个引导类,一些springboot的全局注解(@EnableAutoConfiguration注解)以及springboot程序的入口main方法都放在该类中。
在springboot的程序的基包下(引导类和Controller包在同级目录下),建立TestApplication.class:
内容以下:
@EnableAutoConfiguration public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }
并修改HelloController,去掉main方法及@EnableAutoConfiguration:
@RestController public class HelloController { @GetMapping("show") public String test(){ return "hello Spring Boot!"; } }
启动引导类,访问show测试:
发现全部的Controller都不能访问,为何?
回想之前程序,咱们在配置文件中添加了注解扫描,它能扫描指定包下的全部Controller,而如今并无。怎么解决——@ComponentScan注解
spring框架除了提供配置方式的注解扫描<context:component-scan />
,还提供了注解方式的注解扫描@ComponentScan
。
在TestApplication.class中,使用@ComponentScan注解:
@EnableAutoConfiguration @ComponentScan public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }
从新启动,访问show或者show2:
咱们跟进该注解的源码,并无看到什么特殊的地方。咱们查看注释:
大概的意思:
配置组件扫描的指令。提供了相似与
<context:component-scan>
标签的做用经过basePackageClasses或者basePackages属性来指定要扫描的包。若是没有指定这些属性,那么将从声明这个注解的类所在的包开始,扫描包及子包
而咱们的@ComponentScan注解声明的类就是main函数所在的启动类,所以扫描的包是该类所在包及其子包。通常启动类会放在一个比较浅的包目录中。
咱们如今的引导类中使用了@EnableAutoConfiguration和@ComponentScan注解,有点麻烦。springboot提供了一种简便的玩法:@SpringBootApplication注解
使用@SpringBootApplication改造TestApplication:
@SpringBootApplication public class TestApplication { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }
点击进入,查看源码:
发现@SpringBootApplication实际上是一个组合注解,这里重点的注解有3个:
@SpringBootConfiguration注解的源码:
咱们继续点击查看源码:
经过这段咱们能够看出,在这个注解上面,又有一个@Configuration
注解。经过上面的注释阅读咱们知道:这个注解的做用就是声明当前类是一个配置类,而后Spring会自动扫描到添加了@Configuration
的类,而且读取其中的配置信息。而@SpringBootConfiguration
是来声明当前类是SpringBoot应用的配置类,项目中只能有一个。因此通常咱们无需本身添加。
springboot的默认配置方式和咱们以前玩的配置方式不太同样,没有任何的xml。那么若是本身要新增配置该怎么办?好比咱们要配置一个数据库链接池,之前会这么作:
<!-- 配置链接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean>
如今该怎么作呢?
事实上,在Spring3.0开始,Spring官方就已经开始推荐使用java配置来代替传统的xml配置了,咱们不妨来回顾一下Spring的历史:
Spring1.0时代
在此时由于jdk1.5刚刚出来,注解开发并未盛行,所以一切Spring配置都是xml格式,想象一下全部的bean都用xml配置,细思极恐啊,心疼那个时候的程序员2秒
Spring2.0时代
Spring引入了注解开发,可是由于并不完善,所以并未彻底替代xml,此时的程序员每每是把xml与注解进行结合,貌似咱们以前都是这种方式。
Spring3.0及之后
3.0之后Spring的注解已经很是完善了,所以Spring推荐你们使用彻底的java配置来代替之前的xml,不过彷佛在国内并未推广盛行。而后当SpringBoot来临,人们才慢慢认识到java配置的优雅。
有句古话说的好:拥抱变化,拥抱将来。因此咱们也应该顺应时代潮流,作时尚的弄潮儿,一块儿来学习下java配置的玩法。
java配置主要靠java类和一些注解来达到和xml配置同样的效果,比较经常使用的注解有:
@Configuration
:声明一个类做为配置类,代替xml文件@Bean
:声明在方法上,将方法的返回值加入Bean容器,代替<bean>
标签@Value
:属性注入@PropertySource
:指定外部属性文件。咱们接下来用java配置来尝试实现链接池配置
首先在pom.xml中,引入Druid链接池依赖:
<dependency> <groupId>com.github.drtrang</groupId> <artifactId>druid-spring-boot2-starter</artifactId> <version>1.1.10</version> </dependency>
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/leyou jdbc.username=root jdbc.password=root
建立JdbcConfiguration类:
@Configuration @PropertySource("classpath:jdbc.properties") public class JdbcConfiguration { @Value("${jdbc.url}") String url; @Value("${jdbc.driverClassName}") String driverClassName; @Value("${jdbc.username}") String username; @Value("${jdbc.password}") String password; @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(url); dataSource.setDriverClassName(driverClassName); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } }
解读:
@Configuration
:声明JdbcConfiguration
是一个配置类。@PropertySource
:指定属性文件的路径是:classpath:jdbc.properties
@Value
为属性注入值。dataSource()
方法声明为一个注册Bean的方法,Spring会自动调用该方法,将方法的返回值加入Spring容器中。至关于之前的bean标签而后就能够在任意位置经过@Autowired
注入DataSource了!
咱们在HelloController
中测试:
@RestController public class HelloController { @Autowired private DataSource dataSource; @GetMapping("show") public String test(){ return "hello Spring Boot!"; } }
在test方法中打一个断点,而后Debug运行并查看:
属性注入成功了!
在上面的案例中,咱们实验了java配置方式。不过属性注入使用的是@Value注解。这种方式虽然可行,可是不够强大,由于它只能注入基本类型值。
在SpringBoot中,提供了一种新的属性注入方式,支持各类java基本数据类型及复杂类型的注入。
1)新建JdbcProperties
,用来进行属性注入:
代码:
@ConfigurationProperties(prefix = "jdbc") public class JdbcProperties { private String url; private String driverClassName; private String username; private String password; // ... 略 // getters 和 setters }
在类上经过@ConfigurationProperties注解声明当前类为属性读取类
prefix="jdbc"
读取属性文件中,前缀为jdbc的值。
在类上定义各个属性,名称必须与属性文件中jdbc.
后面部分一致,而且必须具备getter和setter方法
须要注意的是,这里咱们并无指定属性文件的地址,SpringBoot默认会读取文件名为application.properties的资源文件,因此咱们把jdbc.properties名称改成application.properties
2)在JdbcConfiguration中使用这个属性:
经过@EnableConfigurationProperties(JdbcProperties.class)
来声明要使用JdbcProperties
这个类的对象
而后你能够经过如下方式在JdbcConfiguration类中注入JdbcProperties:
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfiguration { @Autowired private JdbcProperties jdbcProperties; @Bean public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(jdbcProperties.getUrl()); dataSource.setDriverClassName(jdbcProperties.getDriverClassName()); dataSource.setUsername(jdbcProperties.getUsername()); dataSource.setPassword(jdbcProperties.getPassword()); return dataSource; } }
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfiguration { private JdbcProperties jdbcProperties; public JdbcConfiguration(JdbcProperties jdbcProperties){ this.jdbcProperties = jdbcProperties; } @Bean public DataSource dataSource() { // 略 } }
@Configuration @EnableConfigurationProperties(JdbcProperties.class) public class JdbcConfiguration { @Bean public DataSource dataSource(JdbcProperties jdbcProperties) { // ... } }
本例中,咱们采用第三种方式。
3)测试结果:
你们会以为这种方式彷佛更麻烦了,事实上这种方式有更强大的功能,也是SpringBoot推荐的注入方式。二者对比关系:
优点:
Relaxed binding:松散绑定
事实上,若是一段属性只有一个Bean须要使用,咱们无需将其注入到一个类(JdbcProperties)中。而是直接在须要的地方声明便可:
@Configuration public class JdbcConfiguration { @Bean // 声明要注入的属性前缀,SpringBoot会自动把相关属性经过set方法注入到DataSource中 @ConfigurationProperties(prefix = "jdbc") public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); return dataSource; } }
咱们直接把@ConfigurationProperties(prefix = "jdbc")
声明在须要使用的@Bean
的方法上,而后SpringBoot就会自动调用这个Bean(此处是DataSource)的set方法,而后完成注入。使用的前提是:该类必须有对应属性的set方法!
咱们将jdbc的url改为:/heima,再次测试:
经过刚才的学习,咱们知道@EnableAutoConfiguration会开启SpringBoot的自动配置,而且根据你引入的依赖来生效对应的默认配置。那么问题来了:
其实在咱们的项目中,已经引入了一个依赖:spring-boot-autoconfigure,其中定义了大量自动配置类:
还有:
很是多,几乎涵盖了如今主流的开源框架,例如:
... 等等
咱们来看一个咱们熟悉的,例如SpringMVC,查看mvc 的自动配置类:
打开WebMvcAutoConfiguration:
咱们看到这个类上的4个注解:
@Configuration
:声明这个类是一个配置类
@ConditionalOnWebApplication(type = Type.SERVLET)
ConditionalOn,翻译就是在某个条件下,此处就是知足项目的类是是Type.SERVLET类型,也就是一个普通web工程,显然咱们就是
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
这里的条件是OnClass,也就是知足如下类存在:Servlet、DispatcherServlet、WebMvcConfigurer,其中Servlet只要引入了tomcat依赖天然会有,后两个须要引入SpringMVC才会有。这里就是判断你是否引入了相关依赖,引入依赖后该条件成立,当前类的配置才会生效!
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
这个条件与上面不一样,OnMissingBean,是说环境中没有指定的Bean这个才生效。其实这就是自定义配置的入口,也就是说,若是咱们本身配置了一个WebMVCConfigurationSupport的类,那么这个默认配置就会失效!
接着,咱们查看该类中定义了什么:
视图解析器:
处理器适配器(HandlerAdapter):
还有不少,这里就不一一截图了。
另外,这些默认配置的属性来自哪里呢?
咱们看到,这里经过@EnableAutoConfiguration注解引入了两个属性:WebMvcProperties和ResourceProperties。
咱们查看这两个属性类:
找到了内部资源视图解析器的prefix和suffix属性。
ResourceProperties中主要定义了静态资源(.js,.html,.css等)的路径:
若是咱们要覆盖这些默认属性,只须要在application.properties中定义与其前缀prefix和字段名一致的属性便可。
SpringBoot为咱们提供了默认配置,而默认配置生效的条件通常有两个:
1)启动器
之因此,咱们若是不想配置,只须要引入依赖便可,而依赖版本咱们也不用操心,由于只要引入了SpringBoot提供的stater(启动器),就会自动管理依赖及版本了。
所以,玩SpringBoot的第一件事情,就是找启动器,SpringBoot提供了大量的默认启动器,参考SpringBoot启动器
2)全局配置
另外,SpringBoot的默认配置,都会读取默认属性,而这些属性能够经过自定义application.properties
文件来进行覆盖。这样虽然使用的仍是默认配置,可是配置中的值改为了咱们自定义的。
所以,玩SpringBoot的第二件事情,就是经过application.properties
来覆盖默认属性值,造成自定义配置。咱们须要知道SpringBoot的默认属性key,很是多,参考SpringBoot全局属性
接下来,咱们来看看如何用SpringBoot来玩转之前的SSM,咱们使用数据库tb_user和实体类User
pom.xml:
<?xml version="1.0" encoding="UTF-8"?> <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>cn.itcast.user</groupId> <artifactId>itcast-user</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
参照上边的项目,编写引导类:
@SpringBootApplication public class UserApplication { public static void main(String[] args) { SpringApplication.run(UserApplication.class); } }
编写UserController:
@RestController @RequestMapping("user") public class UserController { @GetMapping("hello") public String test(){ return "hello ssm"; } }
虽然默认配置已经可使用SpringMVC了,不过咱们有时候须要进行自定义配置。
添加全局配置文件:application.properties
端口经过如下方式配置
# 映射端口 server.port=80
重启服务后测试:
如今,咱们的项目是一个jar工程,那么就没有webapp,咱们的静态资源该放哪里呢?
回顾咱们上面看的源码,有一个叫作ResourceProperties的类,里面就定义了静态资源的默认查找路径:
默认的静态资源路径为:
只要静态资源放在这些目录中任何一个,SpringMVC都会帮咱们处理。
咱们习惯会把静态资源放在classpath:/static/
目录下。咱们建立目录,而且添加一些静态资源:
重启项目后测试:
拦截器也是咱们常常须要使用的,在SpringBoot中该如何配置呢?
拦截器不是一个普通属性,而是一个类,因此就要用到java配置方式了。在SpringBoot官方文档中有这么一段说明:
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own
@Configuration
class of typeWebMvcConfigurer
but without@EnableWebMvc
. If you wish to provide custom instances ofRequestMappingHandlerMapping
,RequestMappingHandlerAdapter
, orExceptionHandlerExceptionResolver
, you can declare aWebMvcRegistrationsAdapter
instance to provide such components.If you want to take complete control of Spring MVC, you can add your own
@Configuration
annotated with@EnableWebMvc
.
翻译:
若是你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器, 视图控制器、消息转换器 等等),你应该让一个类实现
WebMvcConfigurer
,而且添加@Configuration
注解,可是千万不要加@EnableWebMvc
注解。若是你想要自定义HandlerMapping
、HandlerAdapter
、ExceptionResolver
等组件,你能够建立一个WebMvcRegistrationsAdapter
实例 来提供以上组件。若是你想要彻底自定义SpringMVC,不保留SpringBoot提供的一切特征,你能够本身定义类而且添加
@Configuration
注解和@EnableWebMvc
注解
总结:经过实现WebMvcConfigurer
并添加@Configuration
注解来实现自定义部分SpringMvc配置。
实现以下:
首先咱们定义一个拦截器:
@Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("preHandle method is running!"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle method is running!"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion method is running!"); } }
而后定义配置类,注册拦截器:
@Configuration public class MvcConfiguration implements WebMvcConfigurer { @Autowired private HandlerInterceptor myInterceptor; /** * 重写接口中的addInterceptors方法,添加自定义拦截器 * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**"); } }
接下来运行并查看日志:
preHandle method is running! postHandle method is running! afterCompletion method is running!
你会发现日志中只有这些打印信息,springMVC的日志信息都没有,由于springMVC记录的log级别是debug,springboot默认是显示info以上,咱们须要进行配置。
SpringBoot经过logging.level.*=debug
来配置日志级别,*填写包名
# 设置org.springframework包的日志级别为debug logging.level.org.springframework=debug
再次运行查看:
jdbc链接池是spring配置中的重要一环,在SpringBoot中该如何处理呢?
答案是不须要处理,咱们只要找到SpringBoot提供的启动器便可:
在pom.xml中引入jdbc的启动器:
<!--jdbc的启动器,默认使用HikariCP链接池--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--不要忘记数据库驱动,由于springboot不知道咱们使用的什么数据库,这里选择mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
SpringBoot已经自动帮咱们引入了一个链接池:
HikariCP应该是目前速度最快的链接池了,咱们看看它与c3p0的对比:
所以,咱们只须要指定链接池参数便可:
# 链接四大参数 spring.datasource.url=jdbc:mysql://localhost:3306/heima spring.datasource.username=root spring.datasource.password=root # 可省略,SpringBoot自动推断 spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.hikari.idle-timeout=60000 spring.datasource.hikari.maximum-pool-size=30 spring.datasource.hikari.minimum-idle=10
固然,若是你更喜欢Druid链接池,也可使用Druid官方提供的启动器:
<!-- Druid链接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.6</version> </dependency>
而链接信息的配置与上面是相似的,只不过在链接池特有属性上,方式略有不一样:
#初始化链接数 spring.datasource.druid.initial-size=1 #最小空闲链接 spring.datasource.druid.min-idle=1 #最大活动链接 spring.datasource.druid.max-active=20 #获取链接时测试是否可用 spring.datasource.druid.test-on-borrow=true #监控页面启动 spring.datasource.druid.stat-view-servlet.allow=true
SpringBoot官方并无提供Mybatis的启动器,不过Mybatis官方本身实现了:
<!--mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
配置,基本没有须要配置的:
# mybatis 别名扫描 mybatis.type-aliases-package=cn.itcast.pojo # mapper.xml文件位置,若是没有映射文件,请注释掉 mybatis.mapper-locations=classpath:mappers/*.xml
须要注意,这里没有配置mapper接口扫描包,所以咱们须要给每个Mapper接口添加@Mapper
注解,才能被识别。
@Mapper public interface UserMapper { }
user对象:
@Table(name = "tb_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String userName; private String password; private String name; private Integer age; private Integer sex; private Date birthday; private Date created; private Date updated; //getter and setter 省略... }
接下来,就去集成通用mapper。
通用Mapper的做者也为本身的插件编写了启动器,咱们直接引入便可:
<!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency>
不须要作任何配置就可使用了。
@Mapper public interface UserMapper extends tk.mybatis.mapper.common.Mapper<User>{ }
其实,咱们引入jdbc或者web的启动器,就已经引入事务相关的依赖及默认配置了
至于事务,SpringBoot中经过注解来控制。就是咱们熟知的@Transactional
@Service public class UserService { @Autowired private UserMapper userMapper; public User queryById(Long id){ return this.userMapper.selectByPrimaryKey(id); } @Transactional public void deleteById(Long id){ this.userMapper.deleteByPrimaryKey(id); } }
在UserController中添加测试方法,内容:
@RestController @RequestMapping("user") public class UserController { @Autowired private UserService userService; @GetMapping("{id}") public User queryUserById(@PathVariable("id")Long id){ return this.userService.queryById(id); } @GetMapping("hello") public String test(){ return "hello ssm"; } }
咱们启动项目,查看:
完整的pom.xml:
<?xml version="1.0" encoding="UTF-8"?> <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>cn.itcast.user</groupId> <artifactId>itcast-user</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.6.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--jdbc的启动器,默认使用HikariCP链接池--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--不要忘记数据库驱动,由于springboot不知道咱们使用的什么数据库,这里选择mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!-- 通用mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency> </dependencies> </project>
完整的application.properties:
server.port=80 logging.level.org.springframework=debug spring.datasource.url=jdbc:mysql://localhost:3306/heima spring.datasource.username=root spring.datasource.password=root # mybatis 别名扫描 mybatis.type-aliases-package=cn.itcast.pojo # mapper.xml文件位置,若是没有映射文件,请注释掉 # mybatis.mapper-locations=classpath:mappers/*.xml
SpringBoot并不推荐使用jsp,可是支持一些模板引擎技术:
之前你们用的比较多的是Freemarker,可是咱们今天的主角是Thymeleaf!
简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 相似的模板引擎,它能够彻底替代 JSP 。相较于其余的模板引擎,它有以下四个极吸引人的特色:
接下来,咱们就经过入门案例来体会Thymeleaf的魅力:
编写一个controller方法,返回一些用户数据,放入模型中,未来在页面渲染
@GetMapping("/all") public String all(ModelMap model) { // 查询用户 List<User> users = this.userService.queryAll(); // 放入模型 model.addAttribute("users", users); // 返回模板名称(就是classpath:/templates/目录下的html文件名) return "users"; }
直接引入启动器:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
SpringBoot会自动为Thymeleaf注册一个视图解析器:
与解析JSP的InternalViewResolver相似,Thymeleaf也会根据前缀和后缀来肯定模板文件的位置:
classpath:/templates/
.html
因此若是咱们返回视图:users
,会指向到 classpath:/templates/users.html
通常咱们无需进行修改,默认便可。
根据上面的文档介绍,模板默认放在classpath下的templates文件夹,咱们新建一个html文件放入其中:
编写html模板,渲染模型中的数据:
注意,把html 的名称空间,改为:xmlns:th="http://www.thymeleaf.org"
会有语法提示
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>首页</title> <style type="text/css"> table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto} table, th, td {border: 1px solid darkslategray;padding: 10px} </style> </head> <body> <div style="text-align: center"> <span style="color: darkslategray; font-size: 30px">欢迎光临!</span> <hr/> <table class="list"> <tr> <th>id</th> <th>姓名</th> <th>用户名</th> <th>年龄</th> <th>性别</th> <th>生日</th> </tr> <tr th:each="user : ${users}"> <td th:text="${user.id}">1</td> <td th:text="${user.name}">张三</td> <td th:text="${user.userName}">zhangsan</td> <td th:text="${user.age}">20</td> <td th:text="${user.sex}">男</td> <td th:text="${user.birthday}">1980-02-30</td> </tr> </table> </div> </body> </html>
咱们看到这里使用了如下语法:
${}
:这个相似与el表达式,但实际上是ognl的语法,比el表达式更增强大th-
指令:th-
是利用了Html5中的自定义属性来实现的。若是不支持H5,能够用data-th-
来代替
th:each
:相似于c:foreach
遍历集合,可是语法更加简洁th:text
:声明标签中的文本
<td th-text='${user.id}'>1</td>
,若是user.id有值,会覆盖默认的1接下来,咱们打开页面测试一下:
Thymeleaf会在第一次对模板解析以后进行缓存,极大的提升了并发处理能力。可是这给咱们开发带来了不便,修改页面后并不会马上看到效果,咱们开发阶段能够关掉缓存使用:
# 开发阶段关闭thymeleaf的模板缓存 spring.thymeleaf.cache=false
注意:
在Idea中,咱们须要在修改页面后按快捷键:`Ctrl + Shift + F9` 对项目进行rebuild才能够。 eclipse中没有测试过。
咱们能够修改页面,测试一下。