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

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

配置文件生成器-秒杀SSM的xml整合_第1张图片

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

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>

一、生成器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>
  • 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>
  • spring-mybatis-config-template.ftl 模板文件

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/context https://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>

beans>

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

二、生成器代码

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);
    }
}


你可能感兴趣的:(xml)