关于 spring boot 用gradle打包 war后运行的问题

问题描述

打包成jar 运行没有问题
用gradle打包 war后 放入tomcat运行 报错
不知道是那个问题导致的 我运行没错 想问问各位大佬
Failed to instantiate WebApplicationInitializer class

问题出现的环境背景及自己尝试过哪些方法

换了很多jar 都没有用

相关代码

tomcat 日志文件


2-Jul-2019 16:00:10.516 严重 [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Error during ServletContainerInitializer processing
 javax.servlet.ServletException: Failed to instantiate WebApplicationInitializer class
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:155)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5267)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:754)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:730)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1140)
    at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:1875)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.InstantiationException: io.j99.app.measure.Application
    at java.lang.Class.newInstance(Unknown Source)
    at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:152)
    ... 12 more
Caused by: java.lang.NoSuchMethodException: io.j99.app.measure.Application.<init>()
    at java.lang.Class.getConstructor0(Unknown Source)
    ... 14 more

02-Jul-2019 16:00:10.516 严重 [localhost-startStop-1] org.apache.catalina.core.StandardContext.startInternal Context [/measure-0.0.1] startup failed due to previous errors
02-Jul-2019 16:00:10.562 警告 [localhost-startStop-1] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [measure-0.0.1] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
02-Jul-2019 16:00:10.562 信息 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [D:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\measure-0.0.1] has finished in [5,484] ms
02-Jul-2019 16:00:10.562 信息 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [D:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\ROOT]
02-Jul-2019 16:00:10.734 信息 [36] org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
 java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1364)
    at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1021)
    at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.checkContextClassLoaders(AbandonedConnectionCleanupThread.java:96)
    at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:69)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

gradle 构建文件


apply plugin: 'java'
apply plugin: 'org.springframework.boot'
//apply plugin: 'spring-boot'

//apply plugin: 'watch'
apply plugin: 'war'
war {
    baseName = 'measure'
    version = '0.0.1'
}
/*apply plugin: 'idea'
idea {
    module {
        inheritOutputDirs = false
        outputDir = file("$buildDir/classes/main/")
    }
}*/
repositories {
    maven { url "http://maven.aliyun.com/nexus/content/repositories/public/" }
    maven { url "http://repo.spring.io/libs-snapshot" }
}

tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8
springBoot {
    executable = true
}
configurations {
    // providedRuntime
     dev
}
/*jar {
    mainClass = "io.j99.app.measure.Application"
}*/
dependencies {
    compile("commons-logging:commons-logging:1.2")
    compile("javax.servlet:javax.servlet-api:4.0.1")

//
     compile group: 'org.apache.tomcat.embed', name: 'tomcat-embed-jasper', version: '9.0.8'
    compile("org.springframework.boot:spring-boot-devtools")
    //


    compile group: 'org.springframework.boot', name: 'spring-boot-dependencies', version: '2.2.0.M4'
   compile group: 'org.springframework.boot', name: 'spring-boot-maven-plugin', version: '2.2.0.M4'


    ///
     compile ("org.springframework.boot:spring-boot-dependencies")
     compile ("org.springframework.boot:spring-boot-maven-plugin")
    ///

    ////
    compile group: 'cn.org.faster', name: 'spring-boot-starter-parent', version: '1.1.1.RELEASE'
    compile ("org.springframework.boot:spring-boot-starter-tomcat")
    compile ("org.springframework.boot:spring-boot-starter-web")
    compile ("org.springframework.boot:spring-boot-devtools")


    //
    compile "org.springframework.boot:spring-boot-configuration-processor"
    compile("mysql:mysql-connector-java:8.0.12")
    ///
    compile fileTree(dir: 'libs', include: ['*.jar'])
   // dev("org.springframework.boot:spring-boot-devtools")
    testCompile("org.springframework.boot:spring-boot-starter-test")
    compile "io.springfox:springfox-swagger2:2.5.0"
    compile("org.springframework.session:spring-session")
    compile("org.simpleframework:simple-xml:2.7")
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    compile("org.springframework.boot:spring-boot-starter-data-redis")
    compile("org.springframework.boot:spring-boot-starter-data-rest")
    compile 'io.jsonwebtoken:jjwt:0.6.0'
//    compile("org.springframework.boot:spring-boot-starter-data-mongodb")
    compile("org.springframework.boot:spring-boot-starter-jdbc")
    compile("org.springframework.boot:spring-boot-starter-data-jpa")
    compile("org.springframework.boot:spring-boot-starter-actuator")
   // compile("mysql:mysql-connector-java")
    compile("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.6.0")
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-jackson:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
    compile 'com.squareup.okhttp3:okhttp:3.1.2'
    compile("org.springframework.boot:spring-boot-starter-web")
    compile('commons-net:commons-net:3.5')
    compile('com.googlecode.log4jdbc:log4jdbc:1.2')
// https://mvnrepository.com/artifact/org.apache.poi/poi
    compile group: 'org.apache.poi', name: 'poi', version: '3.15'
    compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.15'
// https://mvnrepository.com/artifact/commons-lang/commons-lang
    compile group: 'commons-lang', name: 'commons-lang', version: '2.6'
    compile 'com.qiniu:qiniu-java-sdk:7.2.2'
    // https://mvnrepository.com/artifact/org.apache.ant/ant
    compile group: 'org.apache.ant', name: 'ant', version: '1.10.1'

}
bootRun {
    // addResources = true
   classpath = sourceSets.main.runtimeClasspath + configurations.dev
}

package io.j99.app.measure;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Predicate;
import com.tencent.xinge.XingeApp;
import io.j99.app.measure.db.*;
import io.j99.app.measure.db.model.*;
import io.j99.app.measure.db.model.Package;
import io.j99.app.measure.properties.*;
import io.j99.app.measure.properties.storage.LocalStorageProperties;
import io.j99.app.measure.properties.storage.QiniuStorageProperties;
import io.j99.app.measure.service.DeviceService;
import io.j99.app.measure.service.MessageService;
import io.j99.app.measure.storage.StorageService;
import io.j99.app.measure.utils.Md5;
import io.j99.app.measure.utils.RandomUtils;
import io.swagger.annotations.Api;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.ApiKeyVehicle;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.google.common.base.Predicates.or;
import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.builders.PathSelectors.regex;

@SpringBootApplication
@Configuration
//@ComponentScan("io.j99.app.measure")

@EnableSwagger2
@EnableConfigurationProperties({
        QiniuStorageProperties.class,
        LocalStorageProperties.class,
        AlipayProperties.class,
        AppConfigProperties.class,
        XGProperties.class,
        BaiduProperties.class,
        WXProperties.class,
        YunPianProperties.class})
@EnableJpaRepositories(repositoryFactoryBeanClass = CustomJpaRepositoryFactoryBean.class)
@EnableScheduling
public class Application extends SpringBootServletInitializer {
    Logger logger = LoggerFactory.getLogger(Application.class);
    @Autowired
    private Environment environment;
    @Autowired
    private PackageRepository packageRepository;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AccountRepository accountRepository;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private ObjectMapper objectMapper;
    //    @Autowired
    private XGProperties xgProperties;
    @Autowired
    private ExpertRepository expertRepository;

    @Autowired
    public Application(XGProperties xgProperties) {
        this.xgProperties = xgProperties;
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
        restTemplate.setMessageConverters(converters);
        return restTemplate;
    }

    @Bean
    public XingeApp xingeApp() {
        return new XingeApp(xgProperties.getId(), xgProperties.getSecret());
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    private AppConfigProperties appConfigProperties;
    @Autowired
    private ConfigRepository configRepository;

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            ImageIO.scanForPlugins();
            String profile = environment.getProperty("profile");
            if (!"prod".equalsIgnoreCase(profile)) {
//                loadTestDevice();
//                initTestErrorCode();
//                initTestExport();
                logger.info(appConfigProperties.toString());
            }
            logger.info("Profile name: " + profile);
            logger.info("Database Url: " + environment.getProperty("spring.datasource.url"));
            logger.info("Redis Host: " + environment.getProperty("spring.redis.host"));
            if (adminRepository.count() <= 0) {
                Admin admin = new Admin();
                admin.setName("admin");
                String password;
                if (!"prod".equalsIgnoreCase(profile)) {
                    password = "111111";
                } else {
                    password = UUID.randomUUID().toString().replaceAll("-", "");

                }
                admin.setPassword(password);
                admin.setInitPasswrd(true);
                String salt = RandomUtils.randText(4).toUpperCase();
                String encode = Md5.encode(admin.getPassword() + salt);
                admin.setPassword(salt + encode);
                adminRepository.save(admin);
                logger.info("==================================================");
                logger.info("Init Admin Account:" + admin.getName());
                logger.info("Init Admin Password:" + password);
                logger.info("==================================================");
            }
            if (packageRepository.count() <= 0) {
                Iterable<Package> packages = packageRepository.save(newArrayList(
                        new Package(PackageType.POINT, 10, "10个", 10f),
                        new Package(PackageType.POINT, 100, "100个", 9.99f),
                        new Package(PackageType.POINT, 1000, "1000个", 99.98f),
                        new Package(PackageType.MEASURE, 1, "包月套餐", 0.01f),
                        new Package(PackageType.MEASURE, 3, "季度套餐", 0.01f),
                        new Package(PackageType.MEASURE, 6, "半年套餐", 0.01f),
                        new Package(PackageType.MEASURE, 12, "包年套餐", 0.01f),
                        new Package(PackageType.MEASURE, 999, "永久套餐", 0.01f).setPermanent(true)
                ));
                for (Package pck : packages) {
                    logger.info("init add package: " + pck.toString());
                }
            }
            List<String> asEmail = appConfigProperties.getAsEmail();
            List<String> csEmail = appConfigProperties.getCsEmail();
            List<String> asPhone = appConfigProperties.getAsPhone();
            List<String> csPhone = appConfigProperties.getCsPhone();
            String integralDesc = appConfigProperties.getIntegralDesc();
            String demoAddr = appConfigProperties.getDemoAddr();
            String inviteUrl = appConfigProperties.getInviteUrl();
            String shopUrl = appConfigProperties.getShopUrl();
            if (configRepository.findByName("asEmail") == null) {
                Config entity = new Config();
                entity.setName("asEmail");
                entity.setContent(new JSONArray(asEmail).toString());
                configRepository.save(entity);
            }
            if (configRepository.findByName("csEmail") == null) {
                Config entity = new Config();
                entity.setName("csEmail");
                entity.setContent(new JSONArray(csEmail).toString());
                configRepository.save(entity);
            }
            if (configRepository.findByName("asPhone") == null) {
                Config entity = new Config();
                entity.setName("asPhone");
                entity.setContent(new JSONArray(asPhone).toString());
                configRepository.save(entity);
            }
            if (configRepository.findByName("csPhone") == null) {
                Config entity = new Config();
                entity.setName("csPhone");
                entity.setContent(new JSONArray(csPhone).toString());
                configRepository.save(entity);
            }
            if (configRepository.findByName("integralDesc") == null) {
                Config entity = new Config();
                entity.setName("integralDesc");
                entity.setContent(integralDesc);
                configRepository.save(entity);
            }
            if (configRepository.findByName("demoAddr") == null) {
                Config entity = new Config();
                entity.setName("demoAddr");
                entity.setContent(demoAddr);
                configRepository.save(entity);
            }
            if (configRepository.findByName("inviteUrl") == null) {
                Config entity = new Config();
                entity.setName("inviteUrl");
                entity.setContent(inviteUrl);
                configRepository.save(entity);
            }
            if (configRepository.findByName("shopUrl") == null) {
                Config entity = new Config();
                entity.setName("shopUrl");
                entity.setContent(shopUrl);
                configRepository.save(entity);
            }
            storageService.deleteAll();
            storageService.init();
        };
    }

    private void initTestExport() {
        if (expertRepository.count() <= 0) {
            Iterable<Expert> experts = expertRepository.save(newArrayList(
                    new Expert("陈进", "http://cdn-img.easyicon.net/png/12068/1206805.gif", 10, 0, "陈进搞了十年软件开发经验丰富"),
                    new Expert("陈进2", "http://cdn-img.easyicon.net/png/12068/1206805.gif", 11, 0, "陈进2搞了十一年软件开发经验丰富")
            ));
            for (Expert pck : experts) {
                logger.info("init add expert: " + pck.toString());
            }
        }
    }

    @Autowired
    private ErrorCodeRepository errorCodeRepository;

    private void initTestErrorCode() {
        List<ErrorCode> errorCodes = new ArrayList<>();
        errorCodes.add(new ErrorCode("10011", "电量不足", "立刻充电,立刻充电,立刻充电,立刻充电,立刻充电,立刻充电,立刻充电,立刻充电,立刻充电,立刻充电,立刻充电,立刻充电,立刻充电"));
        errorCodes.add(new ErrorCode("10012", "未检测到探头", "检查探头是否损坏或是否没有安装探头,检查探头是否损坏或是否没有安装探头,检查探头是否损坏或是否没有安装探头,检查探头是否损坏或是否没有安装探头,检查探头是否损坏或是否没有安装探头,检查探头是否损坏或是否没有安装探头,检查探头是否损坏或是否没有安装探头,检查探头是否损坏或是否没有安装探头"));
        errorCodes.add(new ErrorCode("10013", "无法连接设备", "请将设备靠近手机,请将设备靠近手机,请将设备靠近手机,请将设备靠近手机,请将设备靠近手机,请将设备靠近手机,请将设备靠近手机,请将设备靠近手机,请将设备靠近手机,请将设备靠近手机,请将设备靠近手机,请将设备靠近手机"));
        errorCodeRepository.deleteAll();
        for (ErrorCode errorCode : errorCodes) {
            errorCodeRepository.save(errorCode);
            logger.info("add test ErrorCode: " + errorCode.toString());
        }
    }

    private void loadTestDevice() {
        try {
            Resource deviceDir = resourceLoader.getResource("classpath:data/device/");
            String url = deviceDir.getURL().toString();
            logger.info("import device dir {}", url);
            if (deviceDir.exists()) {
                if (deviceDir.getFile().isDirectory()) {
                    File[] files = deviceDir.getFile().listFiles();
                    if (files != null) {
                        List<Device> devices = Arrays.asList(files).parallelStream().map(file -> {
                            try {
                                logger.info("import device info {}", file.toString());
                                return objectMapper.readValue(file, Device.class);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            return null;
                        }).collect(Collectors.toList());
                        logger.info("import device start");
                        deviceService.importDevice(devices);
                        logger.info("import device end");
                        for (Device device : devices) {
                            logger.info("import device {} success!", device.getModel());
                        }
                    } else {
                        logger.info("import device file list is empty");
                    }
                } else {
                    logger.error("data/device must be dir");
                    System.exit(1);
                }
            } else {
                logger.info("device data dir not found");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

    }


    @Bean
    public SecurityConfiguration security() {
        return new springfox.documentation.swagger.web.SecurityConfiguration(
                null, null, null,
                "appName",
                "apiKeyValue",
                ApiKeyVehicle.HEADER,
                Constants.AUTHORIZATION,
                ",");
    }

    @Bean
    public UiConfiguration uiConfig() {
        return new UiConfiguration(
                "validatorUrl",// url
                "none",       // docExpansion          => none | list
                "alpha",      // apiSorter             => alpha
                "schema",     // defaultModelRendering => schema
                UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS,
                true,        // enableJsonEditor      => true | false
                true);        // showRequestHeaders    => true | false
    }

    @Bean
    public Docket newsAdminApi() {
//        AuthorizationScope[] authScopes = new AuthorizationScope[2];
//        authScopes[0] = new AuthorizationScopeBuilder()
//                .scope("read")
//                .description("read access")
//                .build();
//        authScopes[1] = new AuthorizationScopeBuilder()
//                .scope("write")
//                .description("write access")
//                .build();
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("admin")
                .securitySchemes(newArrayList(
                        new ApiKey(Constants.AUTHORIZATION, Constants.AUTHORIZATION, "header")))
                .produces(new HashSet<String>() {{
                    add("application/json");
                }})
                .genericModelSubstitutes(ResponseEntity.class)
                .ignoredParameterTypes(Admin.class)
                .directModelSubstitute(java.time.LocalDate.class, String.class)
                .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
                .directModelSubstitute(java.time.OffsetDateTime.class, Date.class)
                .directModelSubstitute(java.time.LocalDateTime.class, Date.class)
                .globalResponseMessage(RequestMethod.GET, getResponseMessages())
                .globalResponseMessage(RequestMethod.POST, getResponseMessages())
                .globalResponseMessage(RequestMethod.PUT, getResponseMessages())
                .globalResponseMessage(RequestMethod.DELETE, getResponseMessages())
                .globalResponseMessage(RequestMethod.HEAD, getResponseMessages())
                .apiInfo(adminInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(adminPaths())
                .build();
    }

    @Bean
    public Docket newsApi() {
//        AuthorizationScope[] authScopes = new AuthorizationScope[2];
//        authScopes[0] = new AuthorizationScopeBuilder()
//                .scope("read")
//                .description("read access")
//                .build();
//        authScopes[1] = new AuthorizationScopeBuilder()
//                .scope("write")
//                .description("write access")
//                .build();
        return new Docket(DocumentationType.SWAGGER_2)
//                .groupName("user")
                .securitySchemes(newArrayList(
                        new ApiKey(Constants.AUTHORIZATION, Constants.AUTHORIZATION, "header")))
                .produces(new HashSet<String>() {{
                    add("application/json");
                }})
                .genericModelSubstitutes(ResponseEntity.class)
                .ignoredParameterTypes(Account.class)
                .directModelSubstitute(java.time.LocalDate.class, String.class)
                .directModelSubstitute(java.time.ZonedDateTime.class, Date.class)
                .directModelSubstitute(java.time.OffsetDateTime.class, Date.class)
                .directModelSubstitute(java.time.LocalDateTime.class, Date.class)
                .directModelSubstitute(byte[].class, int[].class)
                .globalResponseMessage(RequestMethod.GET, getResponseMessages())
                .globalResponseMessage(RequestMethod.POST, getResponseMessages())
                .globalResponseMessage(RequestMethod.PUT, getResponseMessages())
                .globalResponseMessage(RequestMethod.DELETE, getResponseMessages())
                .globalResponseMessage(RequestMethod.HEAD, getResponseMessages())
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .paths(apiPaths())
                .build();
    }

    private ArrayList<ResponseMessage> getResponseMessages() {
        return newArrayList(
                new ResponseMessageBuilder()
                        .code(400)
                        .message("参数错误")
                        .responseModel(new ModelRef("ExceptionResponse"))
                        .build(),
                new ResponseMessageBuilder()
                        .code(401)
                        .message("未登录或登录信息已过期")
                        .responseModel(new ModelRef("ExceptionResponse"))
                        .build(),
                new ResponseMessageBuilder()
                        .code(499)
                        .message("业务逻辑错误")
                        .responseModel(new ModelRef("ExceptionResponse"))
                        .build());
    }

    private Predicate<String> adminPaths() {
        return or(

                regex("/admin/expert.*"),
                regex("/admin/device.*"),
                regex("/admin/account.*"),
                regex("/admin/misc.*"),
                regex("/admin/user.*"),
                regex("/admin/wallet.*"),
                regex("/admin/message.*"),
                regex("/admin/analyse.*"),
                regex("/admin/package.*"));

    }

    private Predicate<String> apiPaths() {
        return or(
                regex("/api/expert.*"),
                regex("/api/user.*"),
                regex("/api/misc.*"),
                regex("/api/order.*"),
                regex("/api/message.*"),
                regex("/api/device.*"),
                regex("/api/share.*"),
                regex("/api/export.*"),
                regex("/api/pay.*"),
                regex("/api/invite.*"),
                regex("/api/wallet.*"),
                regex("/api/package.*"),
                regex("/api/sync.*"),
                regex("/api/account.*"));
    }

    private ApiInfo adminInfo() {
        return new ApiInfoBuilder()
                .title("测绘app 后台管理Api" + ("develop".equals(environment.getProperty("profile")) ? "(测试环境)" : "(正式环境)"))
//                .description("<a href=\"javascript:void();window.document.location.href.substring(0,window.document.location.href.indexOf(window.document.location.pathname))+'?url=v2/api-docs';\">客户端api</a>")
                .description("<a href=\"?url=v2/api-docs\">客户端api</a>")
//                .termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open")
                .contact(new Contact("henjue", "http://github.com/henjue", "henjue@gmail.com"))
//                .license("Apache License Version 2.0")
//                .licenseUrl("https://github.com/IBM-Bluemix/news-aggregator/blob/master/LICENSE")
                .version("1.0")
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("测绘app在线api文档" + ("develop".equals(environment.getProperty("profile")) ? "(测试环境)" : "(正式环境)"))
                .description("<a href=\"?url=v2/api-docs?group=admin\">后台管理api</a>")
//                .termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open")
                .contact(new Contact("henjue", "http://github.com/henjue", "henjue@gmail.com"))
//                .license("Apache License Version 2.0")
//                .licenseUrl("https://github.com/IBM-Bluemix/news-aggregator/blob/master/LICENSE")
                .version("1.0")
                .build();
    }
}
阅读 4k
2 个回答
新手上路,请多包涵

spring boot 1.4.2.RELEASE

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题