搭建SpringBoots项目:
1、创建一个quickStart的maven项目
2、添加springbootparent或使用import范围引入版本依赖
3、添加spring-boot-starter-web依赖
4、添加@RestController后,spring就知道我们不使用jsp等视图,会自动把项目配置为RESTful应用。
a、省略了MVC的配置
b、如果不使用@RestController,使用Controller,项目可以正常启动,但访问时会报404错误
分析spring boot注解
1、观察@SpringBootApplication注解的源码,它组合了@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan,在老的版本里,不是@SpringBootConfiguration,而是@Configuration。
2、@EnableAutoConfiguration让Spring Boot根据类路径下的jar包依赖为项目进行自动配置。如,当我们只添加了一个依赖——spring-boot-starter-web后,SpringBoot会自动添加Tomcat和SpringMVC的依赖,并对Tomcat和SpringMVC进行自动配置。
3、@ComponentScan,扫描同级包和下级包里的Bean,所以入口类要放在最外层。
关闭SpringBoot的某个自动配置
使用@SpringBootApplication的exclude参数,如
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
application配置文件
SpringBoot使用一个放置在src/main/resources或类路径/config下的全局配置文件application.properties或application.yml,可简单配置如下:
# 默认为8080
server.port=90
#默认为斜杠"/"
server.context-path=/hello
配置规范:在Spring Boot中,context-path、contextPath、CONTEXT_PATH、context-path都是可以的。但是contextpath不行,在两个单词中一定要有表示间隔的方式,可以是驼峰,可以是“_”,可以是“-”。
自动配置
使用了starter,添加了@SpringBootApplication也就添加了@EnableAutoConfiguration,开启了相关的技术配置就不需要我们配置。有很多starter:
spring-boot-starter-amqb
spring-boot-starter-aop
spring-boot-starter-cache
spring-boot-starter-cloud-connectors
spring-boot-starter-jpa
spring-boot-starter-mongodb
spring-boot-starter-rest
spring-boot-starter-freemarker
spring-boot-starter-jdbc
spring-boot-starter-mail
spring-boot-starter-redis
spring-boot-starter-security
spring-boot-starter-thymeleaf
spring-boot-starter-web
spring-boot-starter-tomcat
spring-boot-starter-jetty
spring-boot-starter-logging
spring-boot-starter-log4j
spring-boot-starter-websocket