核心配置文件
两种常用格式
application.properties
application.yml
推荐第二种,递进关系明显,有层次感,配置写得少
SpringBoot项目结构
SpringBoot整合MyBatis,SpringMVC
mybatis的依赖,官方地址 https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter
添加mybatis的依赖 <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
修改application.yml的文件
server:
port: 8086
spring:
datasource:
diver-class-name: com.test
url: jdbc:mysql://localhost:3306/mysql
username: root
password: root
mybatis:
type-aliases-package: com.test
mapper-locations: classpath:com/test/*.xml
创建实体类
创建service接口和实现类
@Component
public class Dept{ private Long deptno; private String dname; private String loc; // get set 方法 }
创建Mapper接口
public interface DeptService{ List<Dept> selectAll(); }
创建Mapper映射文件
public interface DeptService{ List<Dept> selectAll(); } @Service public class DeptServiceImpl implements DeptService{ @Autowired private DeptMapper deptMapper; public void setDeptMapper(DeptMapper deptMapper){ this.deptMapper = deptMapper; } // 查询功能暂时不需要 @ransactional public List<Dept> selectAll(){ return deptMapper.selectAll(); } }
创建Controller处理器
@RestController public class DeptController{ @Autowired private DeptService public void setDeptService(DeptService deptService){ this.deptService = deptService; } @RequeestMapping("/show") public List<Dept> Show(){ return deptService.selectAll(); } }
添加扫描注解
@SpringBootApplication @MapperScan("com.test.mapper") public class LianmaiApplication { public static void main(String[] args) { SpringApplication.run(LianmaiApplication.class, args); } }
SpringBoot整合Druid
添加依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependenyc>
修改application.yml文件
# 连接池配置信息
# 初始化大小: 最大, 最小
druid:
initial-size: 5
min-idle: 5
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测, 检测需要关闭的空闲连接, 单位是ms
time-between-eviction-runs-millis: 60000
# 配置一个连接在池子中最小生存的时间, 单位是ms
min-evictable-idle-time-millis: 3000000
validation-query: select 1
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打开PSCache, 并且指定每个连接上PSCache的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
filter: satat,wall,slf4j
connection-properties: druid.stat.mergesql=true;druid.stat.slowsqlmillis=5000
# 配置DruidStatFilter
web-stat-filter:
enabled: true
url-pattern: "/*"
exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
# 配置DruidStatViewServlet
stat-view-servlet:
url-pattern: "/druid/*"
# IP白名单
allow: 127.0.0.1,192.168.163.1
# IP黑名单(同时存在于白名单时, deny 优先于 allow)
deny: 192.168.1.188
reset-enable: false
# 登录名
login-username: admin
# 登录密码
login-password: 123456
mybatis:
mapper-locations: classpath:com/test/*.xml
启动运行项目
运行期间: 如果抛出错误,java.lang.NoClassDefFoundErrror: org/springframework/boot/bind/RelaxedPropertyResolver
解决方案,改为使用继承的方式实现SpringBoot启动器的依赖,不再使用依赖的方式
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> </parent>
druid的登陆页面 http://localhost:8080/druid
SpringBoot整合logback日志记录
logback是log4j的改良版本,取代原因:实现更快,更充分的测试,更充分的文档
logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!--设置变量LOG_HOME,用于指定log日志文件存放的目录--> <property name="LOG_NAME" value="${catalina.base}/logs/"> <!--控制台输出--> <appender name="Stdout" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -%msg%n</pattern> </layout> </appender> <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBaseRollingPolicy"> <fileNamePattern>${LOG_HOME}/server.%d{yyy-MM-dd}.log</fileNamePattern> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <patterm>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -%msg%n</pattern> </layout> <triggeingPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> </property> <root level="info"> <appender-ref ref="Stdout"/> <appender-ref ref="RollingFile"/> </root> <logger name="com.test.mapper" level="debug"></logger> <!-- 日志异步到数据库 --> <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> <dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource"> <driverClasss>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://127.0.0.1:3306/test</url> <user>root</user> <password>root</password> </dataSource> </connectionSource> </appender> </configuration>
SpringBoot整合thymeleaf
thymelea的效率高于jsp
引入依赖,编写模板
SpringBoot开发者工具包
添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <version>2.1.10.RELEASE</version> <scope>runtime</scope> <optional>true</optional> </dependency>
导入springboot打包插件
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.1.10.RELEASE</version> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build>
设置IDEA的自动编译
使用快捷键
SpringBoot整合分页工具
SpringBoot整合PageHelper,不需要做任何配置,添加依赖后直接只用
添加依赖
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.2.12</version> </dependency>
编写controller代码
@RequestMapping("/showpage") public ModelAndView showpage(Integer pageindex){ ModelAndView mv = new ModelAndView(); if(pageindex == null){ PageHelper.startPage(1, 2); }else{ PageHelper.startPage(pageindex, 2); } List<Dept> list = deptService.findAll(); PageInfo<Dept> pageinfo = new PageInfo<Dept>(list); mv.addObject("pageinfo", pageinfo); return mv; }
SpringBoot的项目打包
如果有jsp,打包成war包,没有jsp,打包成jar包
清除缓存并安装或打包
nvm clean install
或者
nvm clean package
异常显示页面(三种方式)
异常处理方法、类
"服务降级"或者"服务容错"
只局限于当前controller类
@ExceptionHandler(Exception.class) @ResponseBody public String showExe(){ System.out.println("进入showExe控制器里..."); return "出错了, 别着急." }
当前项目所有controller类,都可以走该异常类
@ControllerAdvice public class DemoExecutionClass{ @ExceptionHandler(ArithmeticException.class) @ResponseBody public String showExe(){ System.out.println("进入showExe......"); return "出错了, 别着急" } }
SpringBoot整合Junit
添加依赖
<dependency> <groupId>org.springframework.boot<groupId> <artifactId>spring-boot-starter-test<artifactId> <version>2.1.10.RELEASE<version> </dependency>
创建测试类
@SpringBootTest(classes = SSMApplication.class) @RunWith(SpringJUnit4ClassRunner.class) public class DemoTest{ @Autowired private DeptService deptService; public void setDeptService(DeptService deptService){ this.deptService = deptService; } @Test public void test1(){ List<Dept> list = deptService.selectAll(); System.our.println(list.size()); } }
SpringBoot实现IOC,SpringBoot的Bean管理
创建实体类
public class User{ private int id; private String name; // get set 方法 }
创建配置类
通过bean注解,获得bean对象
@Configuration public class Config{ @Bean protected User jqk(){ User user = new User(); user.setId(1); user.setName("zs"); return user; } @Bean protected User def(){ User user = new User(); user.setId(2); user.setName("ly"); return user; } }
创建启动类
@SpringBootApplication public class MyApplication{ public static void main(String[] args){ SpringApplication.run(MyApplication.class, args); } }
创建测试类
@SpringBootTest(classes = MyApplication.class) @RunWith(SpringJunit4ClassRunner.class) public class MyTest{ private User user; // getter setter 设置 } @Test public void test1(){ System.out.println(user); }
如果配置类中有两个相同返回值类型的方法,测试类该怎么办
@Autowired private Uuser def; public void setDef(User def){ this.def = def; }
@Autowired @Qualifier("edf") private User def; public void setDef(User def){ this.user = user; }
SpringBoot实现DI
实体类
public class Person{ private User user; // getter setter }
配置类
@Bean protected Person per(User jqk){ Person person = new Person(); Person.setUser(jqk); return person; }
修改测试类
@Autowired private Person person; @Test public void test1(){ System.out.println(person); }
SpringBoot整合拦截器
控制器
@Controller public class DemoController{ @RequestMapping("/demo") @ResponseBody public String demo(){ return "demo"; } @RequestMapping("/login") public String login(){ return "login"; } }
创建拦截器
@Component public class MyInterCeptor implements HanderInterceptor{ public boolean preHandler(String[] args){ System.out.println("执行拦截器"); return false; } }
创建配置类
@Configuration public class Config implements WebMvcConfiguration{ @AutoWired private DemoInterCeptor demoInterCeptor; // 配置拦截器的拦截路径 public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(myInterCeptor).addPathPatterns("/**").excludePathPatterns("/login"); } }