• 配置文件生成器-秒杀SSM的xml整合


    配置文件生成器-秒杀SSM的xml整合

    在这里插入图片描述

    思路: 通过简单的配置,直接生成对应配置文件。

    maven坐标

      <dependencies>
        
        <dependency>
          <groupId>org.freemarkergroupId>
          <artifactId>freemarkerartifactId>
          <version>2.3.31version>
        dependency>
        
        <dependency>
          <groupId>mysqlgroupId>
          <artifactId>mysql-connector-javaartifactId>
          <version>8.0.27version>
        dependency>
    
        
        <dependency>
          <groupId>com.alibabagroupId>
          <artifactId>druidartifactId>
          <version>1.2.1version>
        dependency>
        
        <dependency>
          <groupId>javax.servlet.jspgroupId>
          <artifactId>jsp-apiartifactId>
          <version>2.2version>
        dependency>
        
        <dependency>
          <groupId>javax.servletgroupId>
          <artifactId>jstlartifactId>
          <version>1.2version>
        dependency>
    
        
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatisartifactId>
          <version>3.5.2version>
        dependency>
        
        <dependency>
          <groupId>org.mybatisgroupId>
          <artifactId>mybatis-springartifactId>
          <version>2.0.6version>
        dependency>
    
        
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-webmvcartifactId>
          <version>5.2.12.RELEASEversion>
        dependency>
    
        
        <dependency>
          <groupId>com.fasterxml.jackson.coregroupId>
          <artifactId>jackson-databindartifactId>
          <version>2.12.5version>
        dependency>
        
        <dependency>
          <groupId>org.projectlombokgroupId>
          <artifactId>lombokartifactId>
          <version>1.18.30version>
          <scope>compilescope>
        dependency>
        <dependency>
          <groupId>org.springframeworkgroupId>
          <artifactId>spring-jdbcartifactId>
          <version>5.1.9.RELEASEversion>
        dependency>
      dependencies>
      <build>
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      build>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94

    一、生成器ftl模板文件

    模板文件,全部放在resource目录下的template文件夹中 。

    • mybatis-config-template.ftl 模板文件。
    
    DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
       <settings>
            
            <setting name="logImpl" value="STDOUT_LOGGING" />
        settings>
        
        <typeAliases>
            <package name="${packageName}"/>
        typeAliases>
    
        
    
    configuration>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • springmvc-config-template.xml.ftl 模板文件
    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">
    
        
        <context:component-scan base-package="${basePackage}"/>
        
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="${viewResolverPrefix}"/>
            <property name="suffix" value="${viewResolverSuffix}"/>
        bean>
          
        <mvc:resources location="/static/" mapping="/static/**" />
    
        
        <mvc:annotation-driven/>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • spring-mybatis-config-template.ftl 模板文件
    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
        
        <context:component-scan base-package="${basePackage}"/>
    
        
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${dbDriverClassName}"/>
            <property name="url" value="${dbUrl}"/>
            <property name="username" value="${dbUsername}"/>
            <property name="password" value="${dbPassword}"/>
        bean>
    
        
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="mapperLocations" value="${mapperLocations}"/>
            
             <property name="configLocation" value="${mybatisConfigLocation}"/>
        bean>
    
        
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="${daoBasePackage}"/>
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        bean>
    
        
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        bean>
           
        <tx:annotation-driven transaction-manager="transactionManager"/>
    
    beans>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • web-config-template.ftl 模板文件
    
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    
        
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
        listener>
    
        
        <context-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>${springMyBatisConfigPath}param-value>
        context-param>
    
        
        <servlet>
            <servlet-name>DispatcherServletservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>${springMvcConfigPath}param-value>
            init-param>
            <load-on-startup>1load-on-startup>
        servlet>
    
        <servlet-mapping>
            <servlet-name>DispatcherServletservlet-name>
            <url-pattern>/url-pattern>
        servlet-mapping>
    
        
        
        <filter>
            <filter-name>encodingFilterfilter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
            <init-param>
                <param-name>encodingparam-name>
                <param-value>UTF-8param-value>
            init-param>
            <init-param>
                <param-name>forceEncodingparam-name>
                <param-value>trueparam-value>
            init-param>
        filter>
    
        <filter-mapping>
            <filter-name>encodingFilterfilter-name>
            <url-pattern>/*url-pattern>
        filter-mapping>
    
    web-app>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52

    二、生成器代码

    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import freemarker.template.TemplateException;
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    /**
     * 最屌Java实习生  -chen fei
     * 2023/10/6
     */
    public class SSMWebXmlGenerator {
        // SSM 全局参数
        private static final String BASE_PACKAGE = "com.itheima";
        private static final String OUTPUT_DIR = "src/main/resources/ssm";  // 配置文件生成目录
    
        // MyBatis 配置参数
        private static final String MYBATIS_CONFIG_LOCATIONS = "classpath:ssm/mybatis-config.xml";
        private static final String MYBATIS_OUTPUT_PATH = OUTPUT_DIR + "/mybatis-config.xml";  // 设置mybaits配置文件名字
        private static final String POJO_PACKAGE = BASE_PACKAGE + ".pojo"; // typeAliases  设置别名参数
    
        // Spring MVC 配置参数
        private static final String SPRING_MVC_OUTPUT_PATH = OUTPUT_DIR + "/springmvc-config.xml";  //springmvc配置文件名字
        private static final String CONTROLLER_PACKAGE = BASE_PACKAGE + ".controller";   // 配置controller包位置,以便可以扫描到里面的bean
            private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/jsp/";  //视图解析器前缀
        private static final String VIEW_RESOLVER_SUFFIX = ".jsp";//视图解析器后缀
    
        // Spring 配置参数
        private static final String SPRING_OUTPUT_PATH = OUTPUT_DIR + "/spring-mybatis-config.xml";  //spring配置文件名字
        private static final String DAO_PACKAGE = BASE_PACKAGE + ".dao";  // dao层的全包名
        private static final String SERVICE_PACKAGE = BASE_PACKAGE + ".service";  //service层的全包名
        private static final String DB_DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver"; //mysql驱动,默认8.*
        private static final String DB_URL = "jdbc:mysql://localhost:3306/cnmsb";  //url
        private static final String DB_USERNAME = "root"; //账号
        private static final String DB_PASSWORD = "root"; // 密码
        private static final String MYBATIS_MAPPER_LOCATIONS = "classpath*:mapper/*.xml"; //配置mybatis中xml的位置
    
        // web.xml 配置参数
        private static final String WEB_XML_OUTPUT_PATH = "src/main/webapp/WEB-INF/web.xml";   //生成路径
        private static final String SPRING_MYBATIS_CONFIG_PATH = "classpath:ssm/spring-mybatis-config.xml";  //spring配置文件名
        private static final String SPRING_MVC_CONFIG_PATH = "classpath:ssm/springmvc-config.xml"; //springmvc文件名
    
    
        public static void main(String[] args) throws IOException, TemplateException {
            try {
    //            先生成所需目录
                createDirectoriesIfNotExists();
    //            生成mybaits配置文件
                generateMyBatisConfig();
    //            mvc配置文件
                generateSpringMVCConfig();
    //            spring配置文件
                generateSpringConfig();
    //            web.xml配置文件。
                generateWebXml();
            } catch (IOException | TemplateException e) {
                e.printStackTrace();
                System.err.println("生成配置文件时出错:" + e.getMessage());
                System.out.println("请注意,生成配置文件时、请删除或注释pom文件中,build标签。会影响生成!!!");
            }
        }
        private static void createDirectoriesIfNotExists() {
            // Create base package directories
            String[] subPackages = {"pojo", "dao", "service", "controller", "utils"};
            for (String subPackage : subPackages) {
                String packagePath = BASE_PACKAGE.replace('.', '/') + "/" + subPackage;
                File packageDir = new File("src/main/java/" + packagePath);
                if (!packageDir.exists()) {
                    if (packageDir.mkdirs()) {
                        System.out.println("Created package directory: " + packagePath);
                    } else {
                        System.err.println("Failed to create package directory: " + packagePath);
                    }
                }
            }
    
            // Check and create VIEW_RESOLVER_PREFIX directory
            File viewResolverDir = new File("src/main/webapp" + VIEW_RESOLVER_PREFIX);
            if (!viewResolverDir.exists()) {
                if (viewResolverDir.mkdirs()) {
                    System.out.println("Created VIEW_RESOLVER_PREFIX directory: " + viewResolverDir.getPath());
                } else {
                    System.err.println("Failed to create VIEW_RESOLVER_PREFIX directory: " + viewResolverDir.getPath());
                }
            }
    
            // Check and create 'mapper' directory in resources
            File resourcesDir = new File("src/main/resources");
            File mapperDir = new File(resourcesDir, "mapper");
            if (!mapperDir.exists()) {
                if (mapperDir.mkdirs()) {
                    System.out.println("Created 'mapper' directory in resources.");
                } else {
                    System.err.println("Failed to create 'mapper' directory in resources.");
                }
            }
    
            File resourcesDir2 = new File("src/main/resources");
            File mapperDir2 = new File(resourcesDir2, "static");
            if (!mapperDir2.exists()) {
                if (mapperDir2.mkdirs()) {
                    System.out.println("Created 'static' directory in resources.");
                } else {
                    System.err.println("Failed to create 'static' directory in resources.");
                }
            }
        }
    
    
        private static void generateMyBatisConfig() throws IOException, TemplateException {
            // 配置 FreeMarker
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
            configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
            configuration.setDefaultEncoding("UTF-8");
            // 加载 MyBatis 配置模板文件
            Template template = configuration.getTemplate("template/mybatis-config-template.ftl");
    
            Map dataModel = new HashMap<>();
            // 设置 MyBatis 包名参数
            dataModel.put("packageName", POJO_PACKAGE);
    
            generateFile(MYBATIS_OUTPUT_PATH, template, dataModel);
        }
    
        private static void generateSpringMVCConfig() throws IOException, TemplateException {
            // 配置 FreeMarker
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
            configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
            configuration.setDefaultEncoding("UTF-8");
            // 加载 Spring MVC 配置模板文件
            Template template = configuration.getTemplate("template/springmvc-config-template.xml.ftl");
    
            Map dataModel = new HashMap<>();
            // 设置 Spring MVC 包名参数和视图解析器参数
            dataModel.put("basePackage", CONTROLLER_PACKAGE);
            dataModel.put("viewResolverPrefix", VIEW_RESOLVER_PREFIX);
            dataModel.put("viewResolverSuffix", VIEW_RESOLVER_SUFFIX);
    
            generateFile(SPRING_MVC_OUTPUT_PATH, template, dataModel);
        }
    
        private static void generateSpringConfig() throws IOException, TemplateException {
            // 配置 FreeMarker
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
            configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
            configuration.setDefaultEncoding("UTF-8");
            // 加载 Spring 配置模板文件
            Template template = configuration.getTemplate("template/spring-mybatis-config-template.ftl");
    
            Map dataModel = new HashMap<>();
            // 设置 Spring 包名参数和数据库连接参数
            dataModel.put("basePackage", DAO_PACKAGE + "," + SERVICE_PACKAGE);
            dataModel.put("dbDriverClassName", DB_DRIVER_CLASS_NAME);
            dataModel.put("dbUrl", DB_URL);
            dataModel.put("dbUsername", DB_USERNAME);
            dataModel.put("dbPassword", DB_PASSWORD);
            dataModel.put("mapperLocations", MYBATIS_MAPPER_LOCATIONS);
            dataModel.put("mybatisConfigLocation", MYBATIS_CONFIG_LOCATIONS);
            dataModel.put("daoBasePackage", DAO_PACKAGE);
    
            generateFile(SPRING_OUTPUT_PATH, template, dataModel);
        }
    
        private static void generateWebXml() throws IOException, TemplateException {
            // 配置 FreeMarker
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
            configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
            configuration.setDefaultEncoding("UTF-8");
            // 加载 web.xml 配置模板文件
            Template template = configuration.getTemplate("template/web-config-template.ftl");
    
            Map dataModel = new HashMap<>();
            // 设置 web.xml 配置参数,引用之前生成的配置文件路径
            dataModel.put("springMyBatisConfigPath", SPRING_MYBATIS_CONFIG_PATH);
            dataModel.put("springMvcConfigPath", SPRING_MVC_CONFIG_PATH);
    
            generateFile(WEB_XML_OUTPUT_PATH, template, dataModel);
        }
    
        private static Configuration createConfiguration() {
            // 创建 FreeMarker 配置
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
            configuration.setClassForTemplateLoading(SSMWebXmlGenerator.class, "/");
            configuration.setDefaultEncoding("UTF-8");
            return configuration;
        }
    
        private static void generateFile(String outputPath, Template template, Map dataModel)
                throws IOException, TemplateException {
            // 检查父目录是否存在,如果不存在则创建
            File parentDir = new File(outputPath).getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
    
            // 写入文件
            FileWriter writer = new FileWriter(new File(outputPath));
            template.process(dataModel, writer);
            writer.close();
    
            System.out.println("配置文件生成成功:" + outputPath);
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
  • 相关阅读:
    TextView文字图片混排并添加点击事件监听,Textview里面的ImageSpan添加点击响应事件
    「Redis数据结构」字符串对象String
    流式DMA映射实践3:dmaengine与memcpy
    前端如何使用post下载文件(将用户勾选的数据导出、下载),以及下载window.open是预览的文件
    HotSpot的算法实现
    Java--静态字段与静态方法
    对非均匀采样信号进行重采样
    数据挖掘案列分析---LightGBM实战贷款违约预测
    Spring+MyBatis使用collection标签的两种使用方法
    前端食堂技术周刊第 62 期:11 月登陆浏览器的新特性、VueConf 2022、第 93 次 TC39 会议、TS 挑战
  • 原文地址:https://blog.csdn.net/weixin_52236586/article/details/133610521