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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值