配置文件生成器-秒杀SSM的xml整合
思路: 通过简单的配置,直接生成对应配置文件。
maven坐标
xml
<dependencies>
<!-- 配置文件生成 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
<!-- jspapi-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<!-- jstl标签库 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--mybatis、spring整合-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--Springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.12.RELEASE</version>
</dependency>
<!-- mvc、实体类序列化成json。默认jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.5</version>
</dependency>
<!-- lombok插件 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
<build>
<!-- 必选:生成ssm配置文件时,务必把以下内容注释 。项目运行过程mybatis如果报错,再打开、否则保留注释即可。 -->
<!-- <resources>-->
<!-- <!– 静态资源过滤问题解决–>-->
<!-- <resource>-->
<!-- <directory>src/main/java</directory>-->
<!-- <includes>-->
<!-- <include>**/*.properties</include>-->
<!-- <include>**/*.xml</include>-->
<!-- </includes>-->
<!-- <filtering>false</filtering>-->
<!-- </resource>-->
<!-- <resource>-->
<!-- <directory>src/main/resources</directory>-->
<!-- <includes>-->
<!-- <include>**/*.properties</include>-->
<!-- <include>**/*.xml</include>-->
<!-- </includes>-->
<!-- <filtering>false</filtering>-->
<!-- </resource>-->
<!-- </resources>-->
</build>
一、生成器ftl模板文件
模板文件,全部放在resource目录下的template文件夹中 。
- mybatis-config-template.ftl 模板文件。
xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 打印sql日志 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<!-- 设置别名 -->
<typeAliases>
<package name="${packageName}"/>
</typeAliases>
<!-- 其他的MyBatis配置 -->
</configuration>
- springmvc-config-template.xml.ftl 模板文件
xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 配置Controller包扫描 -->
<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/**" />
<!-- 开启SpringMVC的注解 -->
<mvc:annotation-driven/>
</beans>
- spring-mybatis-config-template.ftl 模板文件
xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 扫描dao和service包 -->
<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>
<!-- MyBatis的SqlSessionFactory配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="${mapperLocations}"/>
<!--注入mybatis配置文件-->
<property name="configLocation" value="${mybatisConfigLocation}"/>
</bean>
<!-- MyBatis的MapperScannerConfigurer配置 -->
<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 模板文件
xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- Spring的核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring的核心配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>${springMyBatisConfigPath}</param-value>
</context-param>
<!-- Spring MVC的DispatcherServlet -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>${springMvcConfigPath}</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 其他的Web配置 -->
<!-- 添加UTF-8编码的全局过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
二、生成器代码
Java
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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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);
}
}