欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot创建项目模板

程序员文章站 2022-05-03 09:06:22
...

1、使用IDEA创建项目

1.1 File->new->project->Spring Initializr

springboot创建项目模板

1.2 next

springboot创建项目模板
注意的选择项:Type-Maven或者Gradle Language-语言 Packaging-打包方式 JavaVersion java版本

1.3 next

springboot创建项目模板
要引入的依赖 常用的如SQL->MySQL Driver 等 可以不选择任何一个直接next 后续在pom.xml中手动添加

1.4 next

springboot创建项目模板
项目名称及项目目录

完成即可。

2、常用配置

2.1 项目整体目录

springboot创建项目模板

2.2 application.yml

springboot的配置文件为resources目录下的application.yml或者application.properties
这是2种风格的配置文件,其作用相同。我在这里使用yml方式配置:

#DataSources
spring:
  #数据源
  datasource:
    name: mysql_test
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      filters: stat
      driver-class-name: com.mysql.jdbc.Driver
      #url: jdbc:mysql://172.16.1.216:3306/schoolatu?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull
      username: root
      password: 123456
      initial-size: 5
      max-active: 100
      min-idle: 5
      max-wait: 10000
      min-evictable-idle-time-millis: 3600000
      time-between-eviction-runs-millis: 3600000
      validation-query: SELECT 1
  #请求编码格式
  http:
    encoding:
      force: true
      charset: UTF-8
      enabled: true
#mybatis相关配置
mybatis:
  #mapper文件扫描路径
  mapper-locations: classpath:mapper/*.xml
  #实体类路径
  type-aliases-package: com.yddk.bean
  #驼峰式命名规则:开启
  configuration:
    map-underscore-to-camel-case: true
#tomcat配置
server:
  port: 8080
  tomcat:
    uri-encoding: UTF-8
#日志配置
logging:
  config: classpath:log4j2.yml

2.3 log4j2.yml

日志配置文件,在网上找的,挺全面的配置,原出处忘记是哪里了。

# 共有8个级别,按照从低到高为:ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF。
Configuration:
  status: warn
  monitorInterval: 30
  Properties: # 定义全局变量
    Property: # 缺省配置(用于开发环境)。其他环境需要在VM参数中指定,如下:
    #测试:-Dlog.level.console=warn -Dlog.level.xjj=trace
    #生产:-Dlog.level.console=warn -Dlog.level.xjj=info
    - name: log.level.console
      value: info
    - name: log.path
      value: log
    - name: project.name
      value: sdyddk
    - name: log.pattern
      value: "%d{yyyy-MM-dd HH:mm:ss.SSS} -%5p ${PID:-} [%15.15t] %-30.30C{1.} : %m%n"
  Appenders:
    Console:  #输出到控制台
      name: CONSOLE
      target: SYSTEM_OUT
      PatternLayout:
        pattern: ${log.pattern}
    #   启动日志
    RollingFile:
    - name: ROLLING_FILE
      fileName: ${log.path}/${project.name}.log
      filePattern: "${log.path}/historyRunLog/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
      PatternLayout:
        pattern: ${log.pattern}
      Filters:
        #        一定要先去除不接受的日志级别,然后获取需要接受的日志级别
        ThresholdFilter:
        - level: error
          onMatch: DENY
          onMismatch: NEUTRAL
        - level: debug
          onMatch: ACCEPT
          onMismatch: DENY
      Policies:
        TimeBasedTriggeringPolicy:  # 按天分类
          modulate: true
          interval: 1
      DefaultRolloverStrategy:     # 文件最多100个
        max: 100
    #   平台日志
    - name: PLATFORM_ROLLING_FILE
      ignoreExceptions: false
      fileName: ${log.path}/platform/${project.name}_platform.log
      filePattern: "${log.path}/platform/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
      PatternLayout:
        pattern: ${log.pattern}
      Policies:
        TimeBasedTriggeringPolicy:  # 按天分类
          modulate: true
          interval: 1
      DefaultRolloverStrategy:     # 文件最多100个
        max: 100
    #   业务日志
    - name: BUSSINESS_ROLLING_FILE
      ignoreExceptions: false
      fileName: ${log.path}/bussiness/${project.name}_bussiness.log
      filePattern: "${log.path}/bussiness/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
      PatternLayout:
        pattern: ${log.pattern}
      Policies:
        TimeBasedTriggeringPolicy:  # 按天分类
          modulate: true
          interval: 1
      DefaultRolloverStrategy:     # 文件最多100个
        max: 100
    #   错误日志
    - name: EXCEPTION_ROLLING_FILE
      ignoreExceptions: false
      fileName: ${log.path}/exception/${project.name}_exception.log
      filePattern: "${log.path}/exception/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
      ThresholdFilter:
        level: error
        onMatch: ACCEPT
        onMismatch: DENY
      PatternLayout:
        pattern: ${log.pattern}
      Policies:
        TimeBasedTriggeringPolicy:  # 按天分类
          modulate: true
          interval: 1
      DefaultRolloverStrategy:     # 文件最多100个
        max: 100
    #   DB 日志
    - name: DB_ROLLING_FILE
      ignoreExceptions: false
      fileName: ${log.path}/db/${project.name}_db.log
      filePattern: "${log.path}/db/$${date:yyyy-MM}/${project.name}-%d{yyyy-MM-dd}-%i.log.gz"
      PatternLayout:
        pattern: ${log.pattern}
      Policies:
        TimeBasedTriggeringPolicy:  # 按天分类
          modulate: true
          interval: 1
      DefaultRolloverStrategy:     # 文件最多100个
        max: 100
  Loggers:
    Root:
      level: info
      AppenderRef:
      - ref: CONSOLE
      - ref: ROLLING_FILE
      - ref: EXCEPTION_ROLLING_FILE
    Logger:
    - name: platform
      level: info
      additivity: false
      AppenderRef:
      - ref: CONSOLE
      - ref: PLATFORM_ROLLING_FILE
    - name: bussiness
      level: info
      additivity: false
      AppenderRef:
      - ref: BUSSINESS_ROLLING_FILE
    - name: exception
      level: debug
      additivity: true
      AppenderRef:
      - ref: EXCEPTION_ROLLING_FILE
    - name: db
      level: info
      additivity: false
      AppenderRef:
      - ref: DB_ROLLING_FILE
#    监听具体包下面的日志
#    Logger: # 为com.xjj包配置特殊的Log级别,方便调试
#      - name: com.xjj
#        additivity: false
#        level: ${sys:log.level.xjj}
#        AppenderRef:
#          - ref: CONSOLE
#          - ref: ROLLING_FILE

2.4 pom.xml

maven依赖配置

<?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 https://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.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.sdyd</groupId>
    <artifactId>demo</artifactId>
    <version>1.0</version>
    <name>demo</name>
    <description>demo</description>

    <properties>
        <java.version>1.8</java.version>
        <!-- 文件拷贝时的编码 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- 编译时的编码 -->
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <!--去掉默认日志,加载别的日志 , 切换log4j2日志读取  -->
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- springboot加载包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- MySQL 连接驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>3.1.14</version>
            <scope>runtime</scope>
        </dependency>

        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

        <!-- 分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

        <!-- 加密解密用的包 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <dependency>
            <groupId>bouncycastle</groupId>
            <artifactId>bcprov-jdk14</artifactId>
            <version>138</version>
        </dependency>

        <!-- json转换包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>

        <!-- 处理http请求的包 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.0.CR4</version>
        </dependency>

        <!-- 配置 log4j2 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <!-- 加上这个才能辨认到log4j2.yml文件 -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
        </dependency>

        <!-- 用于连接服务器 并执行操作  类似于FTP工具 -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.53</version>
        </dependency>

        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant</artifactId>
            <version>1.8.4</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains</groupId>
            <artifactId>annotations</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

        <!-- 加密算法相关 -->
        <dependency>
            <groupId>org.jpos</groupId>
            <artifactId>jpos</artifactId>
            <version>1.9.8</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.5 分层以后各层的代码

2.5.1 DemoApplication.java

每个springboot项目都有一个启动入口,默认名称为 “项目名Application
默认代码为

@SpringBootApplication
public class GactivescanApplication {

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

}

在此可能用到的注解

@MapperScan(value = “com.demo.dao”) //用于扫描Dao层以对应Mapper文件

@EnableScheduling //用于开启定时任务

@ImportResource(“classpath:beans.xml”) //用于引入其他配置文件

在这里,我用到一个无法用注解注入的bean(第三方jar包中的内容),所以采用了配置文件的形式
beans.xml内容

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/task
	http://www.springframework.org/schema/task/spring-task-3.0.xsd
    " default-lazy-init="true">

   <bean name="securityService2" class="com.kjtpay.gateway.common.util.security.SecurityService">
   		<!-- 私钥 -->
        <constructor-arg index="0">
            <value>123456</value>
        </constructor-arg>
       <!-- 公钥 -->
        <constructor-arg index="1">
            <value>654321</value>
        </constructor-arg>
    </bean>

</beans>

最后,我的代码为

package com.yddk;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@MapperScan(value = "com.yddk.dao")
@ImportResource("classpath:beans.xml")
@EnableScheduling
public class DemoApplication {

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

}

2.5.2 bean

不多BB,实体层,属性+get方法+set方法,完事。

2.5.3 controller

控制层,在controller目录下,上代码

@RestController
@RequestMapping("/test")
public class TestController {
    private static Logger LOG = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private TestService testService;

    @RequestMapping("/hello")
    public String helloTest() {
        return "SUCCESS";
    }
}

控制访问的路径,如访问helloTest方法的路径为
http://localhost:8080/test/hello

2.5.4 dao

dao层,数据访问层,对数据库的数据CRUD

@Repository
public interface TestDao {
    List<SysConfig> selectSysConfig();
}

只包含了接口

2.5.5 service

服务层,对多个dao进行操作,我这里分为了定义接口和实现

public interface TestService {
    List<SysConfig> getSysConfig();
}
@Service(value = "testService")
public class TestServiceImpl implements TestService{
    @Autowired
    private TestDao testDao;

    @Override
    public List<SysConfig> getSysConfig() {
        return testDao.selectSysConfig();
    }
}

2.5.6 mapper

mapper.xml对应了dao层对数据库的crud
我这里把mapper放在了resources/mapper下

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.yddk.dao.TestDao">
    <sql id="BASE_TABLE">
        sys_config
    </sql>
    <sql id="BASE_COLUMN">
        id,params_key, params_value
    </sql>
    <select id="selectSysConfig" resultType="com.yddk.bean.SysConfig">
        SELECT <include refid="BASE_COLUMN"/>
        FROM <include refid="BASE_TABLE"/>
    </select>
</mapper>

这个配置文件中,namespace对应了具体哪一个Dao,每一个select/insert/update的id对应了Dao中的一个方法。

菜鸟上路,先写到这里,如有问题请大佬指出,谢谢。

相关标签: springboot