SpringBoot的配置文件和注解

本文介绍了如何创建SpringBoot的Maven工程,详细讲解了如何在pom.xml中导入依赖,添加application.yml或application.properties配置文件。同时,文章探讨了log4j2和逆向工程的配置,包括log4j2.xml和generatorConfig.xml的配置内容。最后,阐述了配置文件的位置,以及SpringBoot中启动器代码、Controller、Service层的注解配置情况。
摘要由CSDN通过智能技术生成

SpringBoot

创建maven工程

在pom.xml中导入相应的依赖

<?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>

    <groupId>com.shan</groupId>
    <artifactId>ShanOneZzzfSSHBoot</artifactId>
    <version>1.0-SNAPSHOT</version>
            <!--取代SpringMvc的war包,改为jar包-->
    <packaging>jar</packaging>
<!--SpringBoot的依赖包-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
    </parent>

<!--添加相应的依赖-->
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
                    <!--使项目默认为web项目-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!--log4j2有冲突,排除-->
                <!--使用log4j2打印日志,需要排除该包中自带的logger打印,有冲突-->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- 配置使用redis启动器 -->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- 使用log4j2 打印日志-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
                <!--添加Mybatis和SpringBoot的整合依赖包,为了使用MyBatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- MySQL连接驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
             <!--分页插件的使用-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.12</version>
        </dependency>

        <!--数据库连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.17</version>
        </dependency>


        <!-- 配置使用redis启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!--基于redis的session共享-->
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-data-redis</artifactId>
        </dependency>
                <!--单元测试-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
              <!--Json转换-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>

        <!--逆向工程jar包-->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>
        <!--引入swagger依赖-->
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <!--逆向工程maven插件-->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>


</project>
 

添加application.yml或者application.properties全局配置文件

              application.yml的简单配置

#格式要正确,不能有多余的空格或缩进
#配置tomcat端口号、和虚拟路径
server:
  port: 8080
  servlet:
    context-path: /boot
#配置SpringMVC,下面配置多个数据库需要添加  --- 用于标识不同的配置
spring:
  mvc:
    servlet:
      load-on-startup: 1
  application:
    name: springbootdemo
  profiles:
    active: local
  aop:
    auto: true
    proxy-target-class: false
#配置数据源
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: true
    testOnReturn: false
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    filters: stat,wall,log4j2
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    useGlobalDataSourceStat: true
#配置mybatis
mybatis:
  type-aliases-package: com.pro.conf.domain.*
  mapper-locations: classpath:/mapper/**/*.xml
  configuration:
    map-underscore-to-camel-case: true
    use-generated-keys: true
    default-fetch-size: 100
    default-statement-timeout: 60



---
spring:
  profiles: local
  datasource:
    ddyj:
      username: root
      password: 123456
      url: jdbc:mysql://localhost:3306/ddyj?serverTimezone=Asia/Shanghai&useSSL=false
    test:
      username: root
      password: 123456
      url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useSSL=false
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    pass:



---
spring:
  profiles: staging
  datasource:
    ddyj:
      username: root
      password: 123456
      url: jdbc:mysql://localhost:3306/ddyj?serverTimezone=Asia/Shanghai&useSSL=false
    test:
      username: root
      password: 123456
      url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useSSL=false
  redis:
    database: 3
    host: 127.0.0.1
    port: 6379
    pass:


---
spring:
  profiles: prod
  datasource:
    ddyj:
      username: root
      password: 123456
      url: jdbc:mysql://localhost:3306/ddyj?serverTimezone=Asia/Shanghai&useSSL=false
    test:
      username: root
      password: 123456
      url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useSSL=false
  redis:
    database: 3
    host: 127.0.0.1
    port: 6379
    pass:

log4j2和逆向工程的配置文件

log4j2.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
   <properties>
      <property name="LOG_HOME">/data/serviceLogs/boot-service</property>
      <property name="FILE_NAME">info</property>
      <property name="ERROR_FILE_NAME">error</property>
      <property name="log.sql.level">debug</property>
   </properties>
   <Appenders>
      <Console name="Console" target="SYSTEM_OUT">
         <!--<JsonLayout/>-->
         <PatternLayout charset="UTF-8" pattern="[ %-5level] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n"></PatternLayout>
      </Console>
      <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="${LOG_HOME}/${FILE_NAME}/${FILE_NAME}.log"
                         filePattern="${LOG_HOME}/${FILE_NAME}/$${date:yyyy-MM}/${FILE_NAME}-%d{yyyy-MM-dd}-%i.log">
         <!--<JsonLayout/>-->
         <PatternLayout charset="UTF-8" pattern="[ %-5level] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n"></PatternLayout>
         <Policies>
            <TimeBasedTriggeringPolicy interval="1"/>
            <SizeBasedTriggeringPolicy size="128 MB"/>
         </Policies>
         <DefaultRolloverStrategy max="1000"/>
      </RollingRandomAccessFile>
      <RollingRandomAccessFile name="RollingRandomAccessFileError" fileName="${LOG_HOME}/${ERROR_FILE_NAME}/${ERROR_FILE_NAME}.log"
                         filePattern="${LOG_HOME}/${ERROR_FILE_NAME}/$${date:yyyy-MM}/${ERROR_FILE_NAME}-%d{yyyy-MM-dd}-%i.log">
         <!--<JsonLayout/>-->
         <PatternLayout charset="UTF-8" pattern="[ %-5level] [%date{yyyy-MM-dd HH:mm:ss}] %logger{96} [%line] - %msg%n"></PatternLayout>
         <Policies>
            <TimeBasedTriggeringPolicy interval="1"/>
            <SizeBasedTriggeringPolicy size="128 MB"/>
         </Policies>
         <DefaultRolloverStrategy max="1000"/>
         <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
      </RollingRandomAccessFile>
   </Appenders>
   <Loggers>

      <!-- 如果想看到事务信息把这行注掉即可 -->
      <logger name="org.mybatis" level="DEBUG"></logger>

      <Logger name="com.pro.mapper" level="DEBUG" additivity="false">
         <AppenderRef ref="Console" />
         <AppenderRef ref="RollingRandomAccessFile" />
         <AppenderRef ref="RollingRandomAccessFileError" />
      </Logger>

      <Root level="INFO">
         <AppenderRef ref="Console" />
         <AppenderRef ref="RollingRandomAccessFile" />
         <AppenderRef ref="RollingRandomAccessFileError" />
      </Root>
   </Loggers>
</Configuration>

逆向工程配置文件 generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC
        "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>

    <!--maven命令: mvn mybatis-generator:generate-->

    <!-- 数据库驱动包位置 (需要根据自己的路径修改)-->
    <!--<classPathEntry location="/Users/yangliao/Downloads/apache-maven-3.5.0/mysql_jar/mysql-connector-java-5.1.42.jar"/>-->
    <!--<classPathEntry location="C:\Users\xuanqisong\.m2\repository\mysql\mysql-connector-java\5.1.42\mysql-connector-java-5.1.42.jar"/>-->
    <classPathEntry location="C:\Users\shan\.m2\repository\mysql\mysql-connector-java\8.0.15\mysql-connector-java-8.0.15.jar"/>

    <context id="Tables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- 数据库链接URL、用户名、密码 (定制修改)-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=Asia/Shanghai&amp;useSSL=false"
                        userId="root" password="123456">
            <!--新版本生成属性不全的问题-->
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成模型的包名和位置,实体类 -->
        <javaModelGenerator targetPackage="com.pro.domain"
                            targetProject="./src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 0、生成的映射文件包名和位置,Mapper文件 -->
        <sqlMapGenerator targetPackage="com.pro.mapper"
                         targetProject="./src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--如果生成注解不需要1和2任选一个,一个注解版,一个Xml版Sql -->
        <!-- 1、生成DAO的包名和位置,注解Sql文件, 注解版Mapper文件与SqlProvider在一个文件夹-->
        <!--<javaClientGenerator type="ANNOTATEDMAPPER"
                             targetPackage="com.zichan360.mapper.mapper.zichan360_case"
                             targetProject="E:\javaProject\compensatoryAndAdvance\src\main\java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>-->
        <!--XMLMAPPER-->
        <!--ANNOTATEDMAPPER-->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.pro.mapper"
                             targetProject="./src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 要生成那些表(更改tableName和domainObjectName就可以,多个表的话复制table标签在后边排列即可) -->

     <!--   <table tableName="student" domainObjectName="Student"
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false">
        </table>-->
       <!-- <table tableName="picture" domainObjectName="Picture"
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false">
        </table>-->

    </context>

</generatorConfiguration>

配置文件的位置

1、启动器代码

package com.pro;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

@SpringBootApplication  //开启SpringBootApplication
@EnableRedisHttpSession  //开启Redis共享
@MapperScan("com.pro.mapper")  //扫描mapper包
public class StartPro {
    public static void main(String[] args) {
        SpringApplication.run(StartPro.class,args);  //启动
    }
}

2、控制层Controller层的一般配置

import com.pro.request.LoginParams;
import com.pro.result.ResponseData;
import com.pro.result.ResponseResult;
import com.pro.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/loginController")
public class LoginController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/userLogin")
    @ResponseBody
    public ResponseResult userLogin(LoginParams params, HttpSession session){
        ResponseResult responseResult = userService.userLogin(params);
        Integer code = responseResult.getCode();
        if (code == 200){
            session.setAttribute("userInfo", responseResult.getData());
            return ResponseResult.success("登陆成功");
        }
        return ResponseResult.fail(1001,"登陆失败");
    }
}

3、服务层service.impl层的配置

import com.alibaba.fastjson.JSONObject;
import com.pro.conf.database.DatabaseType;
import com.pro.conf.database.DynamicDataSource;
import com.pro.domain.Student;
import com.pro.domain.User;
import com.pro.mapper.StudentMapper;
import com.pro.mapper.UserMapper;
import com.pro.result.ResponseResult;
import com.pro.service.IDataSourceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
@Component
public class DataSourceServiceImpl implements IDataSourceService {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private UserMapper userMapper;
    @Resource
    private StudentMapper studentMapper;

    @Override
    public ResponseResult dataSourceSwitch() {
        //在默认数据源下,查询当前数据
        User user = userMapper.selectByPrimaryKey(5);
        log.info("dataSourceSwitch::::{}", JSONObject.toJSONString(user));
        //查询test下的student信息
        DynamicDataSource.setDataSourceType(DatabaseType.test);
        Student student = studentMapper.selectByPrimaryKey(4);
        log.info("dataSource(Student):{}",JSONObject.toJSONString(student));
        DynamicDataSource.setDataSourceType(DatabaseType.ddyj);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user",user);
        jsonObject.put("student",student);
        return ResponseResult.success(jsonObject);
    }
}

4、domain层和mapper层不用添加注解

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值