SpringBoot(1)-启动
前言
SpringBoot项目启动,配置,全局异常,Swagger配置,日志处理扩展:
概念
1、引入SpringBoot项目
springboot:https://spring.io/guides/gs/spring-boot/
@SpringBootApplication
注解:@SpringBootApplication
@SpringBootConfiguration
包含:@Configuration
@EnableAutoConfiguration
包含:
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
AutoConfigurationImportSelector:会引入 META-INF/spring.factories 下面组件
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
application.properties配置
server.port=8888
spring.application.name=spring-boot-base
#配置项目路径
server.servlet.context-path=/roc
#配置jsp路径
server.servlet.context-path=/roc
全局异常捕获
@RestControllerAdvice
包含:@ControllerAdvice @ResponseBody
拦截RequestMapping请求,返回json数据给前端
404异常捕获,并返回静态页面
静态文件配置:resources/static
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return (factory -> {
ErrorPage errorPage = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
factory.addErrorPages(errorPage);
});
// WebServerFactoryCustomizer<ConfigurableWebServerFactory> result = new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
// @Override
// public void customize(ConfigurableWebServerFactory factory) {
// ErrorPage errorPage = new ErrorPage(HttpStatus.NOT_FOUND, "/404.do");
// factory.addErrorPages(errorPage);
// }
// };
// return result;
}
事务
开启事务:@EnableTransactionManagement
2、Swagger配置
#swagger配置
roc.swagger.scanPackage=com.today.roc.springboot
roc.swagger.flag=true
roc.swagger.tile=文档名称
roc.swagger.names=维护人
roc.swagger.description=文档描述
<!--swagger配置-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.3</version>
</dependency>
@Data
@ConfigurationProperties(prefix = SwaggerProperties.SWAGGER_PREFIX)
public class SwaggerProperties {
public static final String SWAGGER_PREFIX = "roc.swagger";
/**
* swagger注解扫描范围
*/
private String scanPackage = "";
/**
* swagger在线文档名称
*/
private String tile;
/**
* swagger在线文档描述
*/
private String description;
/**
* 项目维护人员 example
*/
private String names;
/**
* 是否开启swagger true:开启;false:关闭
*/
private String flag;
}
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig {
@Autowired
private SwaggerProperties properties;
@Bean
public Docket createRestApi() {
//添加head参数start
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = Lists.newArrayList();
tokenPar.name("session").defaultValue("00000000-0000-0000-0000-000000000000").description("登陆Session").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
//添加head参数end
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(pars)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(properties.getScanPackage()))
.paths("true".equals(properties.getFlag()) ? PathSelectors.any() : PathSelectors.none())
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(properties.getTile())
.description(properties.getDescription())
.contact(new Contact(properties.getNames(), null, null))
.version("1.0")
.build();
}
}
3、日志
slf4j : 日志门面
#日志级别配置
#默认级别
logging.level.root=INFO
#针对不用包配置不同级别
logging.level.com.today.roc.springboot.base.web=DEBUG
#logfile配置
logging.file.name=D:\\java\\study\\roc-spring-boot\\spring-boot-base\\src\\main\\logs\\info.log
AOP输出日志
@Aspect:定义切面
@Pointcut:设置切点
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
@Slf4j
@Aspect
@Component
public class WebLogAspect {
@Pointcut("execution(public * com.today.roc.springboot.base.web.*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
log.info("URL:{}", request.getRequestURL());
log.info("HTTP METHOD:{}", request.getMethod());
log.info("IP:{}", request.getRemoteAddr());
Enumeration<String> parameterNames = request.getParameterNames();
StringBuffer sb = new StringBuffer();
sb.append("[name:value]:");
while (parameterNames.hasMoreElements()) {
String nextElement = parameterNames.nextElement();
String parameter = request.getParameter(nextElement);
sb.append("[");
sb.append(nextElement);
sb.append(":");
sb.append(parameter);
sb.append("]");
sb.append(",");
}
log.info(sb.toString());
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturn(Object ret) {
log.info(JSONObject.toJSONString(ret));
}
}
4、引入数据库、mybatis
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/roc?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimeZone=UTC&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
spring.datasource.username=root
spring.datasource.password=root
#mybatis扫描配置
mybatis.mapper-locations=classpath*:mybatis/**/*Mapper.xml
5、打包配置
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.today.roc.springboot.base.web.SpringBootBaseApp</mainClass>
<!--如果不设置fork那么不会restart devtools热部署不会起作用-->
<fork>true</fork>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中-->
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>copy-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<type>${project.packaging}</type>
<destFileName>${parent.artifactId}.jar</destFileName>
</artifactItem>
</artifactItems>
<outputDirectory>target</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<useDefaultDelimiters>true</useDefaultDelimiters>
</configuration>
</plugin>
</plugins>
</build>