springboot快速入门

SpringBoot快速入门

springboot是什么?为什么要用?怎么用?
  springboot是为了简化spring的开发的一个轻量级的框架,减少配置,简化maven配置,嵌入tomcat,不需要部署war包

1.添加依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
</parent>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.使用
1.helloworld
新建App启动类,增加注释@EnableAutoConfiguration
@RestController
@EnableAutoConfiguration
public class Application1
{

@RequestMapping("/")
String home() {
return "Hello World!";
}

public static void main( String[] args ) { SpringApplication.run(Application1.class,args); }
}
详见Application1
访问入口:http://localhost:8080
2.启动类使用@SpringBootApplication
详见Application2
访问入口:http://localhost:8080/test/hello
3.与mybatis集成
1.建表t_user 详见:t_user.sql
2.使用mybatis generator 生成model,Dao,xml 依赖mybatis-generator-core
3.依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
4.配置数据源,新建application.properties
5.在UsersMapper增加注解@Mapper 或者在启动类上增加@MapperScan(value = {"com.suns.dao"})
6.新建测试类UserTest 依赖spring-boot-starter-test
@SpringBootTest(classes = {Application3.class})
@RunWith(SpringRunner.class) // SpringJUnit4ClassRunner
public class UserTest {...}
详见UserTest
访问入口:UserTest.testAdd
4.事务支持
1.注意:表的存储引擎要为InnoDB
2.新建IUserService ,UserServiceImpl,增加注解@Transactional
3.在启动类上增加@EnableTransactionManagement
详见UserTest
访问入口:UserTest.testAddBatch
5.全局异常
1.新建ExceptionController#testExeception(), int i=1/0;
2.访问 http://localhost:8080/testExe 会报错 :Whitelabel Error Page
3.解决办法:新建全局异常处理类
@ControllerAdvice
public class GlobalExceptionHandler {}
4.访问一个不存在的路径 http://localhost:8080/testExe12343 又会报错 :Whitelabel Error Page
5.解决办法:
1.在全局异常处理类GlobalExceptionHandler中新增
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){}
2.新建BaseController,一定公共处理的方法
@RequestMapping("/404.do")
public Object error_404() {}

6.静态资源访问,如js,css,图片,html等
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
1.在resources下新建static,放一张图片20190221.png
2.访问http://localhost:8080/20190221.png

7.与jsp集成 (访问不到jsp页面,有问题)
一般来说springboot不建议使用jsp。 而且springboot 内置的tomcat 并没有集成jsp,也没有el表达式。因此如果要使用需要添加依赖
1.依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
2.在application.properties中增加
spring.mvc.view.prefix=/WEB-INF/jsp
spring.mvc.view.suffix=.jsp
3.依次新建webapp目录,WEB-INF目录,jsp目录,index.jsp
4.访问 http://localhost:8080/jsp/index

8.模板引擎thymeleaf
SpringBoot 推荐使用模板引擎来渲染html,如果你不是历史遗留项目,一定不要使用JSP,常用的模板引擎很多,有freemark,thymeleaf等,其实都大同小异其中springboot 强烈推荐的是用thymeleaf
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.注释掉jsp相关jar ,并注释application.properties中jsp的配置
3.新建controller
@Controller
@RequestMapping("/tpl")
public class ThymeleafController {}
4.依次在resources下新建templates目录,testThymeleaf.html 注意:一定要templates,不能是template,不然会找不到
5.访问:http://localhost:8080/tpl/testThymeleaf

9.swagger2 自动生成api文档,并可以在线测试
1.依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2.增加配置类
@EnableSwagger2
@Configuration
public class SwaggerConfig {}
3.新建测试类
@RestController
@RequestMapping(value="/swagger")
public class SwaggerController {}
4.访问入口:http://localhost:8080/swagger-ui.htm

10.日志
般情况下,springboot日志只会输出到控制台,并不会写入到日志文件,但是,在一些正式环境的应用中,我们需要通过在 application.properites 文件中配置 logging.file 文件名称和 logging.path 文件路径,将日志输出到日志文件中

1.在application.properties增加配置
logging.path = e:/log
logging.file = xxx.log
logging.level.root = info
# 配置具体类的日志级别
logging.level.org.springframework.web=debug
logging.level.com.suns.controller.TestContronller=info
logging.level.com.suns.controller.ThymeleafController=debug
注意:如果只配置 logging.path,在 /var/tmp文件夹生成一个日志文件为 spring.log。如果只配置 logging.file,会在项目的当前路径下生成一个 xxx.log 日志文件

默认是使用logback,如果要使用其他的日志框架,需要排除掉logback

2.使用log4j2
<!-- log4j2 ,由于默认使用logback在扩展log4j2之前先要把logback移除-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
3.使用log4j, 一般使用log4j2,而不使用log4j
如果不只为了学习集成log4j,在工作是最好不要使用log4j,毕竟有了log4j2,也有了logback使用log4j就是吃饱了撑着在springboot中并没有提供对log4j这个依赖的支持,因此要使用它配置起来还是挺麻烦的。在: mvnrepository.com 中发现log4j最新版本spring-boot-starter-log4j是1.3.8.RELEAS
1.依赖
<!-- log4j ,由于默认使用logback在扩展log4j2之前先要把logback移除 ,一般不使用log4j,现在已不维护了 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
2.在resources下新建log4j.properties,log4j的日志控制是在log4j.properties,包括日志级别
3.新建Log4jController, private final Logger logger = Logger.getLogger(Log4jController.class); 使用logger输出日志
4.访问入口:http://localhost:8080/log4j/hello
5.就可以看到当前目录下有logs/all.log文件了


11.使用aop对日志进行统一处理
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.增加切面类
@Aspect
@Component
public class WebLogAspect {}
@Pointcut("execution(* com.suns.controller.*.*(..)))") 拦截controller
3.访问入口:http://localhost:8080/test/hello 随意访问一个路径,查看日志输出

12.springboot热加载/热部署 devtools
热部署一般用于开发环境,不会用到生产环境。spring-boot-devtools 是一个为开发者服务的一个模块,其中最重要的功能就是自动应用代码更改到最新的App上面去。原理是在发现代码有更改之后,重新启动应用,但是速度比手动停止后再启动还要更快,更快指的不是节省出来的手工操作的时间
原理:其深层原理是使用了两个ClassLoader,一个Classloader加载那些不会改变的类(第三方Jar包),另一个ClassLoader加载会更改的类,称为 restart ClassLoader,这样在有代码更改的时候,原来的restart ClassLoader 被丢弃,重新创建一个restart ClassLoader,由于需要加载的类相比较少,所以实现了较快的重启时间

1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
2.修改properties文件
如果使用的Thymeleaf 模板,那么请直接在application.properties中添加 spring.thymeleaf.cache=false
如果使用的FreeMarker 模板,那么请直接在application.properties中添加 spring.freemarker.cache=false
3.如果是在idea中使用热加载需要作如下步骤。如果是ecplise,则不需要做如下步骤,只需要ctrl+s就会自动重新编译代码了
1.在pom中增加如下插件
<!-- 用户devtools热部署的插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!-- 如果不设置fork,那么不会restart,devtools热部署不会起作用-->
<fork>true</fork>
</configuration>
</plugin>
2.手动编译:修改完代码,按快捷键Ctrl+F9,手动构建项目,或者只修改单个类文件的话,按Ctrl+Shift+F9,重新编译该类文件,即可触发重启服务
3.自动编译:
1.File -> Settings -> Compiler,勾选 Build Project automatically
2.按快捷键Ctrl+Shift+Alt+/,选择 Registry... ==> 勾选 compiler.automake.allow.when.app.running 即可

3.高级使用
1.集成redis
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.在配置文件application.properties中增加配置:
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=47.107.146.57
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接超时时间(毫秒)
spring.redis.timeout=5000
3.测试类
详见:RedisTest,首先要启动redis服务

2.集成RabbitMQ
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.在配置文件application.properties中增加配置:
spring.rabbitmq.host=47.107.146.57
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
3.RabbitMQ配置类:创建Queue
@Configuration
public class RabbitConfig {
@Bean
public Queue queue(){
// 创建一个队列,名称为:rmq001
return new Queue("rmq001");
}
}
4.生产者
@Component
public class RabbitSender {
@Autowired
private AmqpTemplate amqpTemplate;
public void send(){
amqpTemplate.convertAndSend("rmq001","rabbitmq发送到队列rmp001测试");
System.out.println("生产者:"+"rabbitmq发送到队列rmp001测试");
}
}
5.消费者
@RabbitListener(queues = {"rmq001"})
@Component
public class RabbitReceiver {
@RabbitHandler
public void receive(String msg){
System.out.println("消费者:"+"rabbitmq收到队列rmp001数据:"+msg);
}
}
6.测试类
详见:RabbitMQTest ,首先要启动rabbitmq服务
3.监控管理Actuator
Actuator是spring boot的一个附加功能,可帮助你在应用程序生产环境时监视和管理应用程序。可以使用HTTP的各种请求来监管,审计,收集应用的运行情况.特别对于微服务管理十分有意义
缺点:没有可视化界面(Spring cloud 还会用到这功能,就可以看到界面了)
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2.在application.properties中增加配置
#监控管理actuator
# 加载所有的端点/默认只加载了 info / health
management.endpoints.web.exposure.include=*
#描述信息
info.blog-url=www.test.com
info.author=mk
info.version=v1.0.0
3.测试入口:http://localhost:8080/actuator/info 或 http://localhost:8080/actuator
Actuator访问路径
通过actuator/+端点名就可以获取相应的信息,如
/actuator/beans 显示应用程序中所有Spring bean的完整列表。
/actuator/configprops 显示所有配置信息。
/actuator/env 陈列所有的环境变量。
/actuator/mappings 显示所有@RequestMapping的url整理列表。
/actuator/health 显示应用程序运行状况信息 up表示成功 down失败
/actuator/info 查看自定义应用信息

4.自定义starter
在学习SpringBoot的过程中,不管是集成redis还是RabbitMQ,甚至是前面集成mybatis已经学习了很多starter,这些starter都是springboot为我们提供的一些封装,这些starter能非常方便快捷的增加功能,并不需要很多配置,即使需要配置也就在application.properties稍微配置下就可以了。
那么接下来就学习下怎么创建属于自己的starter,如搭建自己的redis-starter。详见springboot-starter
1.新建空的父项目 springboot-starter
2.新建自己项目 my-redis-starter,只引入spring-boot-starter包,不需要引入spring-boot-starter-web包
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.1</version>
</dependency>
2.新建属性配置类MyRedisProperties
3.新建配置类MyRedisConf
4.依次新建resources目录,META-INF目录,spring.factories文件,内容如下
#配置自定义Starter的自动化配置
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.suns.redis.MyRedisConf
3.新建测试项目 my-redis-starter-test
1.依赖,引入my-redis-starter
<dependency>
<groupId>com.suns</groupId>
<artifactId>my-redis-starter</artifactId>
<version>1.0</version>
</dependency>
2.配置自己的属性
#引入自定义的redis
myredis.host=47.107.146.57
myredis.port=6379
3.测试
详见RedisTest
原理:通过启动类的注解@SpringBootApplication,到@EnableAutoConfiguration,到@Import(AutoConfigurationImportSelector.class)
而AutoConfigurationImportSelector实现了ImportSelector接口,重写selectImports方法,最终是加载META-INF/spring.factories配置文件中的类
在META-INF/spring.factories中可以自定义自己的配置类,然后通过配置类来初始化自己的组件(@Configuration ,@Bean等),如redis,mybaits等
接着只要引入该jar包就可以直接使用里面的组件了,如@Autowired private Jedis jedis

@SpringBootApplication
@EnableAutoConfiguration
@Import(AutoConfigurationImportSelector.class) 实现了ImportSelector接口,重写selectImports方法
public String[] selectImports(AnnotationMetadata annotationMetadata) {}
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
List<String> configurations = getCandidateConfigurations(annotationMetadata,attributes);
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
classLoader.getResources(FACTORIES_RESOURCE_LOCATION);//FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

posted on 2019-03-12 15:49  sgyi06  阅读(177)  评论(0编辑  收藏  举报

导航