1.介绍
springboot可以用很少的配置完成框架快速搭建,因为很多配置都有默认值,之后可以为微服务做基础
运行原理:应用程序的主函数调用run()委托(delegates)给Spring Boot的SpringApplication类,将主程序类Example.class作为参数传给springApplication类-》SpringApplication将引导我们的应用程序,启动Spring,然后启动自动配置的Tomcat Web服务器。Example.class主要的Spring组件
2.如何快速搭建springboot框架
1)创建maven工程
2)在pom.xml中添加

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent>
3)创建主程序

@SpringBootApplication public class Application extends SpringBootServletInitializer{ public static void main(String[] args){ SpringApplication.run(Application.class, args); } } @SpringBootApplication=@Configuration+@EnableAutoConfiguration+@ComponentScan @ComponentScan:全局搜索@Component,@Service,@Repository,@Controller注解的bean到spring上下文环境中 @EnableAutoConfiguration:根据我添加的jar猜我需要的是什么程序然后自动配置 例如:由于spring-boot-starter-web添加了Tomcat和Spring MVC,自动配置将假定您正在开发,Web应用程序并相应地配置Spring。
4)使用程序的小例子

@RestController @RequestMapping("/TyzxAnalysisController") public class TyzxAnalysisController{ @RequestMapping(value="/RequestParamTest") public String RequestParamTest(){ return "helloworld"; } } //之后访问localhost:8080/TyzxAnalysisController就能在前台页面得到helloworld的显示
3.根据需求添加功能
1)如果想要用一个tomcat来管理多个项目
spring-boot默认提供内嵌的tomcat,所以打包直接生成jar包,用java -jar命令就可以启动,但是,有时候我们更希望一个tomcat来管理多个项目,这种情况下就需要项目是war格式的包而不是jar格式的包

1.将项目的启动类Application.java继承SpringBootServletInitializer并重写configure方法 @SpringBootApplication public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args); } } 2.pom.xml中修改 <packaging>jar</packaging>为<packaging>war</packaging> 3.pom.xml中添加tomcat包依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>
2)指定url访问由localhost:8080/变为localhost:8080/aaa就能访问springboot的index.xml页面
在Application.properties中添加server.context-path=/aaa

application.properties
是写配置文件的
也可以改为
application.ymt
3)自定义Banner
在resources文件夹中添加banner.txt自定义想要显示的启动时样子
4)添加监听事件

1)SpringApplication.addListeners(…) ;SpringApplicationBuilder.listeners(…)注册 2)在META-INF / spring.factories文件中添加org.springframework.context.ApplicationListener=com.example.project.MyListener
5)设置启动端口号
–server.port=9000
6)把配置文件改后怎么启动使用自己的配置文件
java -jar myproject.jar --spring.config.name=myproject
java-jarmyproject.jar -spring.config.location=classpath:/default.properties,classpath:/override.properties
7)使用YAML替代 Properties
YAML是JSON的超集SnakeYAML将通过spring-boot-starter自动提供
YamlPropertiesFactoryBean将YAML作为Properties加载,YamlMapFactoryBean将YAML作为Map加载
8)定义实体类方式的使用配置属性
使用@ConfigurationProperties("foo")将配置文件中开头为foo的属性值写入实体类中--->@EnableConfigurationProperties注解注册的属性类以bean配置到spring上下文中
9)配置属性值控制类型转换
当@ConfigurationProperties bean时,spring尝试将程序属性转为正确类型当我们需要自定义类型转化时
1)提供ConversionService bean(使用bean id conversionService)
2)自定义属性编辑器(通过CustomEditorConfigurer bean)
3)自定义转换器(使用注释为@ConfigurationPropertiesBinding的bean定义)
10)约束获得验证从配置文件中获得的值/约束验证映射数据库中实体类
用@Validated注解实体类,@NotNull,@NotEmpty等控制实体类属性值

@ConfigurationProperties(prefix="connection") @Validated public class FooProperties { @NotNull private InetAddress remoteAddress; @Valid private final Security security = new Security(); // ... getters and setters public static class Security { @NotEmpty public String username; // ... getters and setters } }
11)添加日志控制
1)日志写到文件
配置文件中添加logging.file或logging.path
11)自定义图标
类路径根目录查找:favicon.ico有就自动作为应用图标
12)日期格式转化
通过ConfigurableWebBindingInitializer @Bean将转换bean注册到spring中,通过WebBindingInitializer写转换方法
13)模板引擎
FreeMarker,Groovy,Thymeleaf,Mustache
14)指定运行什么环境的配置文件项目
application.properties中默认配置spring.profiles.active =prod---》添加application-dev.properties配置文件写dev环境中特有的设置---》application-prod.properties配置文件中写prod环境中特有的设置
通过命令行指定执行哪个配置文件项目:jar包启动指定--springboot.profile.active=prod
15)添加数据库配置
1)通过Spring-Data-JPA实现对数据的配置
Spring-Data-JPA是对hibernate的整合,在配置文件中添加的配置项目及各自含义
spring.jpa.database=MYSQL
spring.jpa.show-sql=false
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=none(配置Hibernate ddl auto (create, create-drop, update))
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect(根据不同的方言生成符合当前数据库语法的sql)
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy(设置名称的映射策略)
2)使用方法:
写一个接口继承JpaRepository就能通过它操作数据库表
执行curd,只需配置表类@entity,@column等
3)添加事务处理
直接在需要有事务处理的方法上加上@Transactional
16)@Valide表单验证
在实体类具体的属性字段上加@Min(value=18,message="未满18岁禁止入内")
使用这个验证:gridAdd(@Valid Grid gril,BindingResult bindingResult)
之后对表的操作就会有这样的限制验证了
17)项目应用aop切片编程
1)spring-boot-starter-aop
2)创建aspect切片处理程序
aspectJ是使用org.aspectj.lang.JoinPoint接口表示目标类连接点对象,之后可以通过它获得连接点信息这样后调用grilList()方法是就会先执行这里的log()方法

@Aspect @Component public class HttpAspect(){ @Before("execution(public * com.imoc.controller.GridController.grilList(..)))") public void log(){ system.out.println("1111"); } @After("execution(public * com.imoc.controller.GridController.grilList(..)))") public void doAfter(){ system.out.println("1111"); } } //优化的方法 public class HttpAspect(){ @Pointcut("execution(public * com.imoc.controller.GridController.grilList(..)))") public void log(){} @Before("log()") public void log(){ system.out.println("1111"); } @After("log()") public void doAfter(){ system.out.println("1111"); } }
18)对项目统一的异常处理
1)当我们写代码时。出现重复代码,我们要立马优化
创建异常处理类处理异常:
创建hander文件夹创建ExceptionHandler类---》写自己的异常类如GrilException——>创建hander文件夹创建ExceptionHandler类

@ControllerAdvice public class ExceptionHandle{ private final static logger = LoggerFactory.getLogger(ExceptionHandler.class); public Result handle(Exception e){ if(e instanceof GrilException) { GrilException grilException = (GrilException)e; return ResultUtil.error(); }else{ logger.error("系统异常",e) return ResulUtil.error(); } } }
3.注解的含义
1)@RestController和@RequestMapping
通过spring-boot-starter-web添加的springmvc得到其注解控制器,映射器
2)@EnableAutoConfiguration
根据我填的jar猜我需要的是什么程序然后自动配置spring满足我的需求;由于spring-boot-starter-web添加了Tomcat和Spring MVC,自动配置将假定您正在开发 Web应用程序并相应地配置Spring。当有些类不需要配置,这里的自动配置需要这种方式排除他 @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
3)@ComponentScan,@Autowired
识别所有应用程序组件(@Component,@Service,@Repository,@Controller等)将自动注册为Spring Bean;
@Autowired依赖注入:注入方式1:注解在成员属性上
@Autowired
private final RiskAssessor riskAssessor
注入方式2:通过构造函数方式注解属性
private final RiskAssessor riskAssessor;
@Autowired
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
这种注解方式当构造函数注解的bean只有一个的话可以省略@Autowired
4)@SpringBootApplication
相当与@Configuration,@EnableAutoConfiguration和@ComponentScan;还提供了别名来定制@EnableAutoConfiguration和@ComponentScan的属性
5)@ConfigurationProperties
绑定配置文件中属性值到bean中
@ConfigurationProperties(locations = "classpath:mail.properties", ignoreUnknownFields = false, prefix = "mail")
6)@Configuration=@SpringBootConfiguration和@Bean
用@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean。
7)@Profile
可以指定应用程序配置在什么时候加载
8)@value
@value("${name}")能访问资源文件中的值
配置文件中的值用随机值写法:my.secret=${random.value}

<profiles> <profile> <id>dev</id> <properties> <profiles.active>dev</profiles.active> <maven.test.skip>true</maven.test.skip> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>sit</id> <properties> <profiles.active>sit</profiles.active> <maven.test.skip>true</maven.test.skip> </properties> </profile> <profile> <id>prd1</id> <properties> <profiles.active>prd1</profiles.active> <maven.test.skip>true</maven.test.skip> <scope.jar>provided</scope.jar> </properties> </profile> </profiles>
9)@Controller,@RestController
@Controller:必须要配合模板,我这里用thmeleaf,放回的是页面
@RestController=@controller+@responsebody放回的是j'son数据
10)@requestParam,@pathVariable
@requestParam:能获得url中的参数
@pathVariable:能从url中获得一段参数值
4.一些接口作用
1)org.springframework.boot.ExitCodeGenerator
在应用程序结束时返回特定的退出代码
2)ApplicationRunner:CommandLineRunner
提供对应用程序参数的访问,CommandLineRunner:使用上述的ApplicationArguments接口。
5.命令窗口的操作命令(spring-boot-maven-plug提供的能力)
想要使用这些命令需要在pom.xml中添加插件

<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
1).启动程序:根目录输入mvn spring-boot:run
2).编译程序获得jar包或者war包:mvn package
3).查看程序所有依赖包:mvn dependency:tree
4)执行可执行jar:jar java -jar jar包
5)执行可执行jar有调试日志:java -jar jar包 --debug
6)远程调试支持运行打包的应用程序:
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n -jar target/myproject-0.0.1-SNAPSHOT.jar
6.一些工具
1)开发工具:spring-boot-devtools,提供额外的开发时功能

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
功能:在文件被修改时自动重启

SpringApplication.setRegisterShutdownHook(false)时DevTools将无法正常工 2.文件被修改自动重启及时反馈可以设置排除的资源文件 spring.devtools.restart.exclude=static/**,public/** 禁用重启:在application.properties设置spring.devtools.restart.enabled 完全禁止:在SpringApplication.run(…) 之前写System.setProperty("spring.devtools.restart.enabled", "false") 使用触发文件:spring.devtools.restart.trigger-file,设置后改这里就会触发重启 自定义重新启动类加载器:创建一个META-INF / spring-devtools.properties文件 restart.exclude.companycommonlibs=/mycorp-common-[\w-]+.jar restart.include.projectcommon=/mycorp-myproj-[\w-]+.jar 全局配置 iii、spring-boot-devtools模块包括一个嵌入式LiveReload服务器 spring.devtools.livereload.enabled iiii、远程调试项目,远程更新,远程调式通道