AutoConfig介绍

    AutoConfig,主要用于 Maven 项目打包使用。在项目中,我们会将自己写的代码打成 jar 包或者 war 包发布到各种环境上。正常情况下,不用的环境所使用的数据库、缓存的配置是不同的。因此引入了autoConfig插件,在项目打包的时候的动态选择打包配置文件,同时由于相关配置文件非git/svn版本管理,避免了误操作修改了配置value导致错误的风险。

对autoConfig不了解的同学,可以先看一下这里

由于springboot默认是jar包运行,所以本文中autoConfig打包以jar报的目录结构进行配置

JAR包的源文件和目标文件目录结构

jar-project(源目录结构)               -> jar-project.jar(目标目录结构)
 │  pom.xml
 │
 └─src
     └─main
         ├─java
         └─resources                    -> /
             │  file1.xml                      file1.xml
             │  file2.xml                      file2.xml
             │
             └─META-INF                 -> /META-INF
                 └─autoconf             -> /META-INF/autoconf auto-config.xml         auto-config.xml 

SpringBoot使用 maven autoConfig插件打jar包(一)

/META-INF/autoconf目录用来存放AutoConfig的描述文件,以及可选的模板文件。

SpringBoot使用 maven autoConfig插件打jar包(一)

auto-config.xml是用来指导AutoConfig行为的关键描述文件。

创建jar包的AutoConfig机制,关键在于创建jar目标文件中的/META-INF/autoconf/auto-config.xml描述文件。该描述文件对应的maven项目源文件为:/src/main/resources/META-INF/autoconf/auto-config.xml

 

操作步骤:

    1.pom.xml添加autoConfig相关插件

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <!-- 打出的jar包中的 MANIFEST.MF 文件中增加 Main-Class 这一项配置,这样就能在命令行中通过 java -jar 来执行打出的jar包 -->
                        <manifestEntries>
                            <Main-Class>com.xxx.app.pss.WebApplication</Main-Class>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.alibaba.citrus.tool</groupId>
                <artifactId>autoconfig-maven-plugin</artifactId>
                <version>1.2</version>
                <configuration>

                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>autoconfig</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    2.在resoures下建立META-INF文件夹(如果不存在)

    3.在META-INF文件夹下建立autoconf文件夹,用于存放autoConfig相关配置xml以及配置vm模板

    4.在上一步建立的autoConfig下建立auto-config.xml文件

    文件夹目录如下所示:

    SpringBoot使用 maven autoConfig插件打jar包(一)

    5.auto-config.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <group>
        <property name="server.port" defaultValue="9990" description="web项目端口号"/>
        <property name="spring.datasource.driverClassName" defaultValue="com.mysql.jdbc.Driver" description="mysql驱动"/>
        <property name="spring.datasource.url"
                  defaultValue="jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false"
                  description="pss数据库连接信息"/>
        <property name="spring.datasource.username" defaultValue="root" description="datasource username"/>
        <property name="spring.datasource.password" defaultValue="123456" description="datasource password"/>
        <property name="spring.datasource.type" defaultValue="com.alibaba.druid.pool.DruidDataSource"
                  description="连接池类型"/>
        <property name="spring.datasource.initialSize" defaultValue="5" description="连接池初始化大小"/>
        <property name="spring.datasource.minIdle" defaultValue="5" description="连接池最小空闲连接数"/>
        <property name="spring.datasource.maxActive" defaultValue="30" description="连接池中可同时连接的最大的连接数"/>
        <property name="spring.datasource.maxWait" defaultValue="60000" description="获取连接等待超时的时间"/>
        <property name="spring.datasource.timeBetweenEvictionRunsMillis" defaultValue="60000"
                  description="间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒"/>
        <property name="spring.datasource.minEvictableIdleTimeMillis" defaultValue="300000"
                  description="一个连接在池中最小生存的时间,单位是毫秒"/>
        <property name="spring.datasource.validationQuery" defaultValue="SELECT 1 FROM DUAL"
                  description="连接池validationQuery"/>
        <property name="spring.datasource.testWhileIdle" defaultValue="true" description="连接池testWhileIdle"/>
        <property name="spring.datasource.testOnBorrow" defaultValue="false" description="连接池testOnBorrow"/>
        <property name="spring.datasource.testOnReturn" defaultValue="false" description="连接池testOnReturn"/>
        <property name="spring.datasource.filters" defaultValue="stat,wall,log4j" description="连接池监控统计拦截的filters"/>
        <property name="spring.datasource.poolPreparedStatements" defaultValue="true" description="连接池打开PSCache"/>
        <property name="spring.datasource.maxPoolPreparedStatementPerConnectionSize" defaultValue="false"
                  description="连接池指定每个连接上PSCache的大小"/>
        <property name="spring.datasource.connectionProperties"
                  defaultValue="druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000"
                  description="打开mergeSql功能;慢SQL记录"/>
        <property name="mybatis.typeAliasesPackage" defaultValue="com.xxx.app.pss.domain"
                  description="mybatis隐射对象package"/>
        <property name="mybatis.mapperLocations" defaultValue="classpath:mapper/*.xml" description="mapper xml位置"/>
        <property name="mybatis.configuration.logimpl" defaultValue="org.apache.ibatis.logging.slf4j.Slf4jImpl"
                  description="日志记录"/>
        <property name="pagehelper.autoDialect" defaultValue="true" description="分页插件"/>
        <property name="pagehelper.closeConn" defaultValue="true" description="分页关闭连接"/>
        <property name="mapper.mappers" defaultValue="com.xxx.app.pss.common.mapper.MyMapper"
                  description="通用mapper接口"/>
        <property name="mapper.notEmpty" defaultValue="false" description="insert和update中,是否判断字符串类型!=''"/>
        <property name="mapper.identity" defaultValue="MYSQL" description="mysql"/>
        <property name="biz.maxTotalConnections" defaultValue="800" description="最大总连接数"/>
        <property name="biz.maxRouteConnections" defaultValue="400" description="每个路由最大连接数"/>
        <property name="biz.connectTimeout" defaultValue="10000" description="连接超时"/>
        <property name="biz.readTimeout" defaultValue="20000" description="读取超时时间"/>

    </group>
    <script>
        <generate template="application.properties.vm" destfile="application.properties" charset="utf-8"/>
    </script>
</config>

注意:上面的script标签,是根据application.properties.vm 模板文件的内容去生成打包好的文件中的 application.properties 配置文件。

其中的destfile,由于本文是jar包的autoConfig,jar包不同与war包,最后生成的目标文件里没有/WEB-INF文件夹,因此这边的destfile,要根据你的打包类型来匹配:

jar:

destfile="application.properties"

war:

destfile="/WEB-INF/classes/config/application.properties"

表 13.8. 定义property时可用的参数

参数名 说明
name Property名称。
defaultValue(可选) 默认值。默认值中可包含对其它property的引用,如${petstore.work}/logs
description(可选) 对字段的描述,这个描述会显示给deployer,这对他理解该property非常重要。
required(可选) 是否“必填”,默认为true。如果deployer未提供必填项的值,就会报错。

    6.创建 application.properties.vm 模板文件

#端口号
server.port=${server_port}
#数据源配置
spring.datasource.driverClassName=${spring_datasource_driverClassName}
spring.datasource.url=${spring_datasource_url}
spring.datasource.username=${spring_datasource_username}
spring.datasource.password=${spring_datasource_password}
##druid连接池配置
spring.datasource.type=${spring_datasource_type}
# 初始化大小,最小,最大
spring.datasource.initialSize=${spring_datasource_initialSize}
spring.datasource.minIdle=${spring_datasource_minIdle}
spring.datasource.maxActive=${spring_datasource_maxActive}
# 配置获取连接等待超时的时间
spring.datasource.maxWait=${spring_datasource_maxWait}

# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=${spring_datasource_timeBetweenEvictionRunsMillis}
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=${spring_datasource_minEvictableIdleTimeMillis}
spring.datasource.validationQuery=${spring_datasource_validationQuery}
spring.datasource.testWhileIdle=${spring_datasource_testWhileIdle}
spring.datasource.testOnBorrow=${spring_datasource_testOnBorrow}
spring.datasource.testOnReturn=${spring_datasource_testOnReturn}
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=${spring_datasource_filters}
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=${spring_datasource_poolPreparedStatements}
spring.datasource.maxPoolPreparedStatementPerConnectionSize=${spring_datasource_maxPoolPreparedStatementPerConnectionSize}
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=${spring_datasource_connectionProperties}
## Mybatis 配置
mybatis.typeAliasesPackage=${mybatis_typeAliasesPackage}
mybatis.mapperLocations=${mybatis_mapperLocations}
mybatis.configuration.logimpl=${mybatis_configuration_logimpl}
#pagehelper分页插件
pagehelper.autoDialect=${pagehelper_autoDialect}
pagehelper.closeConn=${pagehelper_closeConn}
#通用mapper
mapper.mappers=${mapper_mappers}
mapper.notEmpty=${mapper_notEmpty}
mapper.identity=${mapper_identity}
#http配置
biz.maxTotalConnections=${biz_maxTotalConnections}
#每个路由最大连接数
biz.maxRouteConnections=${biz_maxRouteConnections}
#连接超时
biz.connectTimeout=${biz_connectTimeout}
#读取超时时间
biz.readTimeout=${biz_readTimeout}

注意:这里的 ${server_port} 应该和第 5 步的 auto-config.xml 文件中配置的 property 子节点 name 属性对应

为什么不是${server.port} ???

application.properties.vm,其实就是velocity的模板文件,所以文件中的配置写法必须满足velocity的语法.

例 13.11. 使用不符合velocity语法的placeholders

例如,下面的placeholder被velocity看作非法:

${my.property.2}

解决的办法是,改写成如下样式:

${my_property_2}

所以,application.properties.vm文件中的${}中的'.',都被替换成了'_'.

 

到此位置,springboot 的autoConfig打包配置已经完成,不过在进行下一步之前,还得再检查一下application.properties.vm文件和auto-config.xml中的name是否一一对应,是否有漏的写错的,如果有错误,执行去打包命令,autoConfig会提示你 'xxx文件未准备好'

如果检查无误,进行下一步

由于目前项目中的配置文件是在resources下的application.properties,正常情况下这个properties肯定是测试开发的配置文件,如果需要根据不同环境打不同的包,则需要根据不同环境创建不同的properties.

在桌面或者其他非项目工程文件夹下创建生产环境配置文件:antx-pss.properties 文件名可以自定义

antx中的内容,key必须和application中保持一致,value自定义....

创建好生产环境配置文件后,我们执行打包命令开始打包:

mvn -U -B -f /Users/admin/xxx/app-pss/web/web-base/pom.xml clean package -Dweb -Dmaven.test.skip=true -Dautoconfig.userProperties=/Users/admin/Desktop/antx-pss.properties -Dautoconfig.interactive=false
参数说明:
-U:强制去远程参考更新snapshot包
-B:该参数表示让Maven使用批处理模式构建项目,能够避免一些需要人工参与交互而造成的挂起状态
-f:--file <file> 强制使用备用的POM文件
-Dweb:到web module下打包,-Dadmin 同理
-Dautoconfig.userProperties:指定需要打包的配置文件,根据实际目录,实际文件名替换

仔细观察控制台输出,有如下一段info

[INFO] -------------------------------------------------
Loading file:/Users/admin/Desktop/antx-pss.properties
User-defined properties: file:/Users/admin/Desktop/antx-pss.properties

<jar:file:/Users/admin/xxx/app-pss/web/target/web-0.0.1-SNAPSHOT.jar!/>
    Generating META-INF/autoconfig/application.properties.vm [utf-8] => application.properties [utf-8]

<jar:file:/Users/admin/xxx/app-pss/web/target/web-0.0.1-SNAPSHOT.jar!/>
    Generating log file: META-INF/autoconfig/auto-config.xml.log

[INFO]                                                             

表示通过模板创建对应的配置文件

如果控制台提示文件未准备好,请检查你打包命令中的配置文件属性是不是和vm模板中一致!

最终控制台显示 success 表示打包成功 到target目录下查看对应打包的jar

 

如何指定autoConfig指定打包文件:

13.4.5.3. 指定user properties

默认情况下,AutoConfig会按下列顺序查找user properties:

  1. 当前目录/antx.properties

  2. 当前用户HOME目录/antx.properties

但你可以指定一个自己的properties文件,用下面的命令:

运行AutoConfig独立可执行程序
autoconfig ... –u my.props
运行AutoConfig maven插件
mvn ... -Dautoconfig.userProperties=my.props

因此,上述打包命令中的 -Dautoconfig.userProperties=/Users/admin/Desktop/antx-pss.properties

就是指定了参与打包的配置文件

如果第一次打包的时候,在mvn命令中不指定参与打包的配置文件,AutoConfig会提示你修改user properties文件,以提供所需要的properties值

例 13.17. 交互式编辑properties

╭───────────────────────┈┈┈┈
│
│ 您的配置文件需要被更新:
│
│ file:/.../antx.properties
│
│ 这个文件包括了您个人的特殊设置,
│ 包括服务器端口、您的邮件地址等内容。
│
└───────┈┈┈┈┈┈┈┈┈┈┈

 如果不更新此文件,可能会导致配置文件的内容不完整。
 您需要现在更新此文件吗? [Yes][No] y

当你通过交互式界面填写了所有properties的值,并通过了AutoConfig的验证以后,AutoConfig就开始生成配置文件:

即将保存到文件"file:/.../antx.properties"中, 确定? [Yes][No] y

╭───────────────────────┈┈┈┈
│ 保存文件 file:/.../antx.properties...
│┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈
│petstore.loggingLevel  = warn
│petstore.loggingRoot   = ${petstore.work}/logs
│petstore.upload        = ${petstore.work}/upload
│petstore.work          = /tmp
└───────┈┈┈┈┈┈┈┈┈┈┈
 已保存至文件: file:/.../antx.properties
Loading file:/.../antx.properties
<jar:file:/.../Work/my/apps/petstore-webx3/target/petstore.war!/>
    Generating WEB-INF/web.xml [UTF-8] => WEB-INF/web.xml [UTF-8]

<jar:file:/.../Work/my/apps/petstore-webx3/target/petstore.war!/>
    Generating WEB-INF/common/resources.xml [UTF-8] => WEB-INF/common/resources.xml [UTF-8]

<jar:file:/.../Work/my/apps/petstore-webx3/target/petstore.war!/>
    Generating log file: META-INF/autoconf/auto-config.xml.log

Expanding: /.../Work/my/apps/petstore-webx3/target/petstore.war
       To: /.../Work/my/apps/petstore-webx3/target/petstore
done.

假如发现模板中某个placeholder,并未在auto-config.xml中定义,就会出现以下错误:

ERROR - Undefined placeholders found in template:
- Template:   META-INF/autoconf/WEB-INF/web.xml
- Descriptor: META-INF/autoconf/auto-config.xml
- Base URL:   file:/.../Work/my/apps/petstore-webx3/target/petstore/
---------------------------------------------------------------
-> petstore.loggingRoot
---------------------------------------------------------------

出现错误以后,Maven会报错,并停止build过程。

 

autoConfig的初步配置到这里就结束了,可以愉快的开始玩耍了~

本文中的 例xx.xx,参考自https://blog.csdn.net/Chenbug666/article/details/83965737 autoConfig工具指南

转载请注明出处!

 

相关文章: