1.springboot的参数设置
1.application.properties语法
server.port=80
server.session-timeout=30
server.tomcat.uri-encoding=UTF-8
spring.datasource.url = jdbc:mysql://localhost:3306/crm
spring.datasource.username = root
spring.datasource.password = mymysql
spring.datasource.driverClassName = com.mysql.jdbc.Driver
2.application.yml语法
server:
port: 80
session-timeout: 30
tomcat.uri-encoding: UTF-8
spring:
datasource:
url : jdbc:mysql://localhost:3306/crm
username : root
password : mymysql
driverClassName : com.mysql.jdbc.Driver
3.application.properties优先级
- 项目/config/application.properties
- 项目/application.properties
- classpath:config/application.properties
- classpath:application.properties
2.数据库连接池
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///crm?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
使用的是阿里的连接池
3.事务管理
直接在业务层实现类上或者其方法上直接贴@Transactional注解即可
#SpringBoot默认优先选择CGLIB代理,如果需要改为优先使用JDK代理,需要做以下配置
spring.aop.proxy-target-class=false #优先使用JDK代理
4.继承WEB
默认的静态资源放在resources/static下
动态资源放在templates 例如jsp/ftl
路径映射配置
#在匹配模式时是否使用后缀模式匹配
spring.mvc.pathmatch.use-suffix-pattern=true
集成freemarker
#一般我们会做1个配置,其余默认即可
#暴露session对象的属性
spring.freemarker.expose-session-attributes=true
5.统一异常处理
springboot出现错误的时候,会把他交给classpath:static/error/404.html(其他错误)
@ControllerAdvice //控制器增强器
public class ExceptionControllerAdvice {
@ExceptionHandler(Exception.class) //处理什么类型的异常
public String handlException(Exception e, Model model) {
model.addAttribute("msg", e.getMessage());
return "errorView"; //逻辑视图名称
}
}
6.添加拦截器
之前我们需要其写标签去注册我们自定义的拦截器,在springboot中只需要让我们的配置对象实现webmvcconfiguer接口,实现接口中add…方法即可
@Component
public class LoginInterceptor implements HandlerInterceptor { }
@Component
public class PermissionInterceptor implements HandlerInterceptor { }
@Configuration
public class MvcJavaConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Autowired
private PermissionInterceptor permissionInterceptor;
public void addInterceptors(InterceptorRegistry registry) {
// 注册登录拦截器
registry.addInterceptor(loginInterceptor)
// 对哪些资源起过滤作用
.addPathPatterns("/**")
// 对哪些资源起排除作用
.excludePathPatterns("/logout.do","/loginUser.do","/login.html","/css/**","/js/**");
// 注册登录拦截器
registry.addInterceptor(permissionInterceptor)
// 对哪些资源起过滤作用
.addPathPatterns("/**")
// 对哪些资源起排除作用
.excludePathPatterns("/logout.do","/loginUser.do","/login.html","/css/**","/js/**");
}
}
7.类中使用日志输出
使用lombook提供的注解来简化代码
@Slf4j
@Service
public class PermissionServiceImpl implements IPermissionService {}
log.info(...);
log.error(...);
...
//输出日志中有变量可以使用{}作为占位符
log.info("删除id为{}的数据", id);
``
```bash
#把日志级别修改为debug,不过我们一般不会更改,除非要调试找bug,不然控制台显示的内容太多也容易乱
logging.level.root=debug