Java 项目中常用配置总结

Java 项目常用配置文件整理

1 Maven 相关

1.1 Maven 资源过滤

Maven 的约定大于配置,所以只会识别 resources 目录下的配置文件,别处的配置文件无法别扫描

<!--在 build 中配置 resources,来防止资源导出失败问题-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>
1.2 Maven 阿里镜像
<!--Maven 阿里云镜像-->
<mirror>
    <id>aliyunmaven</id>
    <mirrorOf>*</mirrorOf>
    <name>ali public repository</name>
    <url>https://maven.aliyun.com/repository/public</url>
</mirror>

2 MyBatis 相关

2.1 mybatis-config.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>
    <!--引入 配置文件-->
    <properties resource="db.properties"/>

    <!--设置日志类型-->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

    <!--设置别名-->
    <typeAliases>
        <typeAlias type="com.jiuxiao.pojo.User" alias="User"/>
        <package name="com.jiuxiao.pojo"/>
    </typeAliases>

    <!--环境配置-->
    <environments default="development">
        <!--默认为 development 环境-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    
    <!--Mapper 映射-->
    <mappers>
        <mapper resource="com/jiuxiao/mapper/UserMapper.xml"/>
    </mappers>
</configuration>
2.2 MyBatis 的 SQL 映射
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
2.3 MyBatis 工具类
public class MyBatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        String resource = "mybatis-config.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}
2.4 db.properties
# 数据库基本连接信息
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ ?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username=root
password=0531

# 连接参数配置
jdbc.initialPoolSize=10
jdbc.maxPoolSize=100
jdbc.minPoolSize=10
jdbc.acquireIncrement=10
2.5 log4j.properties
#日志输出目的地
log4j.rootLogger=DEBUG,console,file

#console 输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#file 输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/jiuxiao.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#log 输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
2.6 ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">

    <!--
        diskStore : 缓存目录,Ehcache 分为内存和磁盘两级,此属性定义磁盘的缓存位置
        user.home : 用户主目录
        user.dir  : 用户当前工作目录
        java.io.tmpdir : 默认临时文件路径
    -->
    <diskStore path="./tmpdir/Tmp_Ehcache"/>

    <!-- defaultCache : 默认的缓存策略,当 ehcache 找不到时,则会使用这个缓存策略,只能定义一个默认缓存策略 -->
    <defaultCache
            eternal="false"
            maxElementsInMemory="10000"
            overflowToDisk="false"
            timeToIdleSeconds="1800"
            timeToLiveSeconds="259200"
            memoryStoreEvictionPolicy="LRU"/>

    <cache name="cloud_user"
           eternal="false"
           maxElementsInMemory="5000"
           overflowToDisk="false"
           diskPersistent="false"
           timeToIdleSeconds="1800"
           timeToLiveSeconds="1800"
           memoryStoreEvictionPolicy="LRU"/>
    <!--
        cache 参数解析:
            name : 缓存名称
            maxElementsInMemory : 缓存的最大数目
            maxElementsOnDisk   : 硬盘最大缓存数目
            eternal : 对象是否永久有效,一旦设置为 true,timeout 将不再起作用
            overflowToDisk : 当系统宕机时,是否保存到磁盘中
            timeToIdleSeconds : 对象在失效之前允许的闲置时间(单位:秒),仅当 eternal=false 时才使用
            timeToLiveSeconds : 对象在失效之前允许的存活时间(单位:秒),仅当 eternal=false 时才使用
            diskPersistent : 是否缓存虚拟机重启期间的数据
            diskSpoolBufferSizeMB : 设置磁盘缓存区的大小,默认为 30MB,每个 Cache 都要有自己的大小
            diskExpiryThreadIntervalSeconds : 磁盘失效线程运行时间间隔,默认 120 秒
            memoryStoreEvictionPolicy : 当缓存达到 maxElementsInMemory 设置的最大值时, Ehcache 会根据指定的策略去情路缓存,默认为 LRU 算法
                可选策略有 : FIFO (先进先出算法)、LRU (近期最少使用算法)、LFU (一直最少使用算法)
            clearOnFlush : 内存数量最大时是否进行清理
    -->
</ehcache>

3 JavaWeb 相关

3.1 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_4_0.xsd"
         version="4.0"
         metadata-complete="true">
</web-app>
3.2 Dao层基础公共类
public class BaseDao {

    private static final String driver;
    private static final String url;
    private static final String username;
    private static final String password;

    static {
        Properties properties = new Properties();
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("application.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }

    //获取数据库连接
    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    //查询公共方法
    public static ResultSet execute(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet,String sql, Object[] params) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }

    //增删改公共方法
    public static int execute(Connection connection, PreparedStatement preparedStatement, String sql, Object[] params) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        return preparedStatement.executeUpdate();
    }

    //关闭连接,释放资源
    public static boolean closeResource(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        boolean flag = true;

        if (resultSet != null) {
            try {
                resultSet.close();
                resultSet = null;   //GC回收
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
                preparedStatement = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (connection != null) {
            try {
                connection.close();
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }
}
3.3 字符编码过滤器
public class characterEncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        chain.doFilter(request, response);
    }

    public void destroy() {}
}

未完待续
posted @ 2022-04-26 22:16  悟道九霄  阅读(153)  评论(0编辑  收藏  举报