springboot样例 pom与小花招

 

 首页

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**

 * @classname DefaultPage
 * @Description //TODO
 * @Date 2:42 PM 5/14/2020
 * version 1.0
 **/
@Controller
@RequestMapping("/")
@Slf4j
public class DefaultPage {

    @RequestMapping("/")
    public String index(){
        return "newpage/hello";
    }

}

application.properties 

server.port=8002
spring.auto.openurl=false
spring.web.loginurl=http://127.0.0.1:8002/webContext/newpage/hello.html
spring.web.googleexcute=C:\\Users\\xxxx\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe
# 前缀
spring.mvc.view.prefix=/webContext/
# 后缀
spring.mvc.view.suffix=.html

与配置文件搭配实现启动后自动打开浏览器

package com.example.astest.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**

 * @classname MyCommandRunner
 * @Description // 配置文件加cmd执行实现启动后自动打开网页
 * @Date 11:40 AM 3/22/2019
 * version 1.0
 **/

@Component
public class MyCommandRunner implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(MyCommandRunner.class);
    @Value("${spring.web.loginurl}")
    private String loginUrl;

    @Value("${spring.web.googleexcute}")
    private String googleExcutePath;

    @Value("${spring.auto.openurl}")
    private boolean isOpen;

    @Override
    public void run(String... args) throws Exception {
        if(isOpen){
            String cmd = googleExcutePath +" "+ loginUrl;
            Runtime run = Runtime.getRuntime();
            try{
                run.exec(cmd);
                logger.debug("启动浏览器打开项目成功");
            }catch (Exception e){
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        }
    }
}

 

application,yml 设置多个环境配置

spring:
  profiles:
    active: dev

application-dev.yml

server:
  port: 8003

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.example.entity

#showSql
logging:
  level:
    com:
      example:
        mapper : debug

properties在yml之后加载,会覆盖

log设置 logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。
scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒当scan为true时,此属性生效。默认的时间间隔为1分钟。
debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。
-->

<configuration debug="true" scan="true" scanperiod="1800 seconds">
    <!-- 控制台输出 -->
    <property name="catalina.base" value="E:\1" />
    <!--<property name="catalina.base" value="E:\temp_log\springboottest" />-->


    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} time:%r thread:[%thread] logfrom:%logger{50} type: %-5p message:%m%n</pattern>
        </encoder>
    </appender>
    <!-- 按照每天生成日志文件 -->
    <appender name="DEFAULT-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${catalina.base}/logs/common-default.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名 -->
            <FileNamePattern>${catalina.base}/logs/common-default-%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数 -->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小 -->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
    <!-- 按照每天生成日志文件 -->
    <appender name="INFO-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${catalina.base}/logs/info-log.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名 -->
            <FileNamePattern>${catalina.base}/logs/info-log-%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数 -->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!-- 格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小 -->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
    <!-- 指定某一个包或者某一个类的打印级别以及是否传入root进行打印 -->
    <!-- addtivity:是否向上级loger传递打印信息。默认是true。-->
    <!-- <loger>可以包含零个或多个<appender-ref>元素,标识这个appender将会添加到这个loger。-->
    <!-- name:用来指定受此loger约束的某一个包或者具体的某一个类。-->
    <!-- level:
            用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
            如果未设置此属性,那么当前loger将会继承上级的级别。-->
    <!-- 为所有开头为dao的类打印sql语句 -->
    <!-- <logger name="dao" level="DEBUG">
        <appender-ref ref="INFO-APPENDER" />
    </logger> -->
    <!--
    <logger name="cn.com.aia" level="DEBUG" additivity="true">
        <appender-ref ref="INFO-APPENDER" />
    </logger>
    -->
    <logger name="com.secbro.drools" level="DEBUG" additivity="true"/>
    <!-- 也是<loger>元素,但是它是根loger。只有一个level属性,应为已经被命名为"root". -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT"/>
        <!--<appender-ref ref="DEFAULT-APPENDER"/>-->
    </root>
</configuration>

解决跨域

package com.example.astest.demo.config;


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**

 * @classname CorsConfig
 * @Description //解决跨域问题
 * @Date 10:32 AM 5/15/2020
 * version 1.0
 **/
@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }

}

匹配后缀

package com.example.astest.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**

 * @classname WebMvcConfigurerLocal
 * @Description // mvc设置 springmvc
 * @Date 11:02 AM 5/15/2020
 * version 1.0
 **/
@Configuration
public class WebMvcConfigurerLocal implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        //开启路径后缀匹配
        configurer.setUseRegisteredSuffixPatternMatch(true);
    }


}

main+匹配后缀

package com.example.astest.demo;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.PropertySource;

import org.springframework.web.servlet.DispatcherServlet;


/**
 * @author me
 */
@PropertySource("application.properties")
@SpringBootApplication
//
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) 不配置数据库
public class DemoApplication { public static void main(String[] args) 
{
SpringApplication.run(DemoApplication.
class, args);
}

/** * 设置匹配.do后缀的请求 * @param dispatcherServlet */
@Bean
public ServletRegistrationBean servletRegistrationBean(DispatcherServlet dispatcherServlet) {
ServletRegistrationBean
<DispatcherServlet> servletServletRegistrationBean = new ServletRegistrationBean<>(dispatcherServlet);
servletServletRegistrationBean.addUrlMappings(
"*.do","*.action"); return servletServletRegistrationBean;
}
}

 代码依赖注入 

package com.example.astest.demo.diachieve;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**

 * @classname TheInterfaceConfig
 * @Description //TODO
 * @Date 11:33 AM 7/3/2019
 * version 1.0
 **/
@Configuration
public class TheInterfaceConfig {
    @Bean(name="tone")
    public TheInterfaceClass getOneClass(){
        return new InterfaceAchieveOneImpl();
    }
    @Bean(name="ttow")
    public TheInterfaceClass getTwoClass(){
        return new InterfaceAchieveTwoImpl();
    }
    @Bean(name="real")
    public AbstrantClass getRealClass(){
        return new  RealClass();
    }
}
package com.example.astest.demo.diachieve;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;

/**

 * @classname Test
 * @Description //TODO
 * @Date 10:34 AM 7/3/2019
 * version 1.0
 **/
@Component
@ComponentScan

public class Test {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(TheInterfaceConfig.class);
        TheInterfaceClass  theInterfaceClass=(TheInterfaceClass) ctx.getBean("ttow");
        theInterfaceClass.printResult();
    }
}

 

pom设置  去除了spring自带的test  

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>zerotosecurity</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<junit.platform.version>1.2.0</junit.platform.version>
<junit.engine.version>5.2.0</junit.engine.version>
<jmockit.version>1.41</jmockit.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>${jmockit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.engine.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.engine.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.26</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.26</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>
<version>0.1.5</version>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
<version>4.8</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.11.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<!-- this is needed or IntelliJ gives junit.jar or junit-platform-launcher:1.3.2 not found errors -->
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>mysql</groupId>-->
<!-- <artifactId>mysql-connector-java</artifactId>-->
<!-- <version>8.0.13</version>-->
<!-- <scope>runtime</scope>-->
<!-- </dependency>-->
</dependencies>
<build>
<finalName>dong</finalName>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.8</version>
<configuration>
<includes></includes>
</configuration>
<executions>
<!--这个report:对代码进行检测,然后生成index.html在 target/site/index.html中可以查看检测的详细结果 -->
<!-- report这个就是生成代码覆盖率报告,发生在default生命周期的verify阶段 -->
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<!-- or some other version -->
<configuration>
<argLine>
<!-- 配置命令行参数-->
-javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
-javaagent:${settings.localRepository}/org/jacoco/org.jacoco.agent/0.7.8/org.jacoco.agent-0.7.8-runtime.jar=destfile=${project.basedir}/target/jacoco.exec
</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>

关于sonarqube扫描jmockit

sonar.projectKey=777777777
sonar.projectName=777777777777
sonar.projectVersion=1.0
sonar.sources=./src/main/java
sonar.tests=./src/test
sonar.java.binaries=./target
sonar.language=java
sonar.sourceEncoding=UTF-8
sonar.dynamicAnalysis=reuseReports
#sonar.core.codeCoveragePlugin=jacoco
#sonar.jacoco.reportPaths=./tmp/coverage-reports/jacoco-unit.exec
sonar.core.codeCoveragePlugin=cobertura
sonar.cobertura.reportPaths=./tmp/coverage.ser
sonar.exclusions=**/*.jasper,**/*.jrxml,**/*.XML,**/*.sql,**/vo/**/*,**/77.java

 

posted @ 2020-05-14 16:45  大哥超帅  阅读(552)  评论(0编辑  收藏  举报