SpringBoot基础工程
1.依赖
<!--springboot工程需要继承的父工程-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<!--web开发的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.启动类
@SpringBootApplication
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class,args);
}
}
SpringBoot整合Junit
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.编写测试类
springboot: 2.1.x版本
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HelloApplication.class)//如果测试类和启动类在同一个包下classes属性可以不写。如果不是就要指定启动类的字节码对象
public class BootTest {
@Autowired
private UserService userService;
@Test
public void testJunit(){
System.out.println(userService.test());
}
}
springboot : 2.2.x版本
@SpringBootTest
class BootTest {
@Autowired
private UserService userService;
@Test
public void testJunit(){
System.out.println(userService.test());
}
}
SpringBoot整合Mybatis
1.依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.配置数据库信息
spring:
datasource:
url: jdbc:mysql:///test?serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
3.配置mybatis相关配置
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml # mapper映射文件路径
type-aliases-package: com.itheima.mybatisdemo.domain
4.编写Mapper接口 注意在接口上加上@Mapper 和@Repository 注解
@Repository
@Mapper
public interface UserMapper {
public List<User> findAll();
}
5.编写mapper接口对应的xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.itheima.mybatisdemo.dao.UserMapper">
<select id="findAll" resultType="com.itheima.mybatisdemo.domain.User">
select * from sys_user
</select>
</mapper>
###SpringBoot整合Redis
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置Redis地址和端口号
spring:
redis:
host: 127.0.0.1 #redis服务器ip地址
port: 6379 #redis端口号
3.注入RedisTemplate使用
@Autowired
private RedisTemplate redisTemplate;
@Test
void testRedis(){
Object test = redisTemplate.boundValueOps("test").get();
System.out.println(test);
}
###SpringBoot切换服务器
当我们要开发web项目的时候一般都会引入spring-boot-starter-web这个启动器。这个启动器默认会依赖tomcat的包。这个情况下SpringBoot的就会自动去使用tomcat作为服务器。
如果想切换服务器可以把spring-boot-starter-web中tomcat的依赖排除,然后引入其它服务器的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!--排除tomcat依赖-->
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!--引入jetty依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
SpringBoot配置拦截器
创建拦截器类
package com.*.*.interceptor;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.*.*.*.User;
/**
*
*
* @Package: com.*.*.interceptor
* @ClassName: AdminInterceptor
* @Description:拦截器
* @author: zk
* @date: 2019年9月19日 下午2:20:57
*/
public class AdminInterceptor implements HandlerInterceptor {
/**
* 在请求处理之前进行调用(Controller方法调用之前)
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// System.out.println("执行了TestInterceptor的preHandle方法");
try {
//统一拦截(查询当前session是否存在user)(这里user会在每次登陆成功后,写入session)
User user=(User)request.getSession().getAttribute("USER");
if(user!=null){
return true;
}
response.sendRedirect(request.getContextPath()+"你的登陆页地址");
} catch (IOException e) {
e.printStackTrace();
}
return false;//如果设置为false时,被请求时,拦截器执行到此处将不会继续操作
//如果设置为true时,请求将会继续执行后面的操作
}
/**
* 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
// System.out.println("执行了TestInterceptor的postHandle方法");
}
/**
* 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// System.out.println("执行了TestInterceptor的afterCompletion方法");
}
}
配置拦截器
package com.*.*.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.*.*.interceptor.AdminInterceptor;
/**
*
*
* @Package: com.*.*.config
* @ClassName: LoginConfig
* @Description:拦截器配置
* @author: zk
* @date: 2019年9月19日 下午2:18:35
*/
@Configuration
public class LoginConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册TestInterceptor拦截器
InterceptorRegistration registration = registry.addInterceptor(new AdminInterceptor());
registration.addPathPatterns("/**"); //所有路径都被拦截
registration.excludePathPatterns( //添加不拦截路径
"你的登陆路径", //登录
"/**/*.html", //html静态资源
"/**/*.js", //js静态资源
"/**/*.css", //css静态资源
"/**/*.woff",
"/**/*.ttf"
);
}
}
SpringBoot应用监控
①RestFul接口
#####1.依赖
创建工厂时添加
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yTAzX9pm-1607397126483)(D:\工作\产出\md\畅购api\SpringBoot\img\image-20200409162028156.png)]
自己添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
#####2.配置
# 开启健康检查的完整信息
management.endpoint.health.show-details=always
# 开启所有的健康检查
management.endpoints.web.exposure.include=*
#####3.访问
http://localhost:8080/actuator
②图形化界面SpringBoot Admin
SpringBoot Admin 有两个角色,客户端(Client)和服务端(Server)。
把要被监控的服务作为客户端。提供图形化界面的服务作为服务端
admin-server:
######①创建 admin-server 模块
######②导入依赖坐标 admin-starter-server
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HMgwOsgo-1607397126484)(D:/BaiduNetdiskDownload/2020-散课/SpringBoot/day02/笔记/img/1571812312998.png)]
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-server</artifactId>
<version>2.2.1</version>
</dependency>
######③在引导类上启用监控功能@EnableAdminServer
@EnableAdminServer
@SpringBootApplication
public class SpringbootAdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootAdminServerApplication.class, args);
}
}
#####admin-client(要被监控的服务)
######①创建 admin-client 模块
######②导入依赖坐标 admin-starter-client
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-starter-client</artifactId>
<version>2.2.1</version>
</dependency>
######③配置相关信息:server地址等
# 执行admin.server地址
spring.boot.admin.client.url=http://localhost:9000
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*
spring:
boot:
admin:
client:
url: http://localhost:8888 # 服务端的地址
management:
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: "*"
注意:要求必须是web项目才会注册到服务端
######④启动server和client服务,访问server
http://localhost:8888/
SpringBoot打包
SpringBoot 项目开发完毕后,支持两种方式部署到服务器:
①jar包(官方推荐) 不用修改直接打包就可以 然后 java -jar jar包路径就可以启动
②war包
更改pom文件中的打包方式为war
修改启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class SpringbootDeployApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(SpringbootDeployApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(SpringbootDeployApplication.class);
}
}
指定打包的名称
<build>
<finalName>springboot</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>