2
前言:对于使用配置文件已经有了一定经验的初学者来说,应该体验一下使用注解作为配置文件的感受,一下我用自己的经验来配置一份最简单但同时也全面的配置。安利一篇自己的 Maven自定义SpringBoot 更方便快捷的启动项目, 特别适合毕业设计和小型项目。

1、目录结构

目录结构应该是搭建项目的说明中首先说明的东西,这是涉及到学习者对整体结构了解的一个前提。
clipboard.png

clipboard.png

2、pom文件配置

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cogitationsoft</groupId>
    <artifactId>findit</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>findit Maven Webapp</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <encoding>UTF-8</encoding>
        <java.version>1.8</java.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <junit.version>4.12</junit.version>
        <spring.version>4.3.14.RELEASE</spring.version>
        <servlet.api.version>3.1.0</servlet.api.version>
        <fastjson.version>1.2.46</fastjson.version>
        <mybatis.version>3.4.1</mybatis.version>
        <mybatis.spring.version>1.3.0</mybatis.spring.version>
        <mysql.connector.version>5.1.41</mysql.connector.version>
        <pagehelper.version>5.1.2</pagehelper.version>
        <log4j.version>2.10.0</log4j.version>
        <druid.version>1.1.9</druid.version>
        <freemarker.version>2.3.23</freemarker.version>
        <jackson.version>2.5.4</jackson.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!--spring reply on -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--servlet-api-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.api.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- /com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>

        <!-- log4j-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <!-- mybatis 和 mysql -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>

        <!-- database connection pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>${freemarker.version}</version>
        </dependency>
        <!-- Jackson Json处理工具包 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>findit</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <!-- Config: Maven Tomcat Plugin -->
                <!-- http://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin%20-->
                <plugin>
                    <groupId>org.apache.tomcat.maven</groupId>
                    <artifactId>tomcat7-maven-plugin</artifactId>
                    <version>2.2</version>
                    <!-- Config: contextPath and Port (Default: /SpringMVCFreeMarker : 8080) -->
                    <configuration>
                        <path>/</path>
                        <port>8080</port>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

3、web.xml配置

这里需要做一个说明,因为在全注解配置的配置文件中, web.xml 并不是必需要的,但也可以保留,并且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_3_1.xsd"
         version="3.1"
         metadata-complete="false">
    <display-name>Archetype Created Web Application</display-name>
    <welcome-file-list>
        <welcome-file></welcome-file>
    </welcome-file-list>
</web-app>

如果你保留了web.xml配置文件那么必须把 metadata-complete设置为fasle。可以设置welcome-file来作为根目录的首页, 当然你也可以通过Controller去设置。

4、Log4j2配置信息

clipboard.png
官方文档中有这样的说明,当你是用Log4j2的时候会自动加载classpath下的名为图片中的那些配置文件,并且按照1~10是有优先级的,取名的时候要注意这个问题,并且在2.x开始到2.4是不支持properties的配置的,默认使用xml配置,在2.4之后又新加回了properties配置。详细配置请看官方文档。

#属性表示log4j2本身的日志信息打印级别
status = DEBUG
#如果犯错,url,路径等结果输出到strerr中
dest = err
#log4j 2.6 之前和 之后的 配置不同 ,2.6 之后 ,当第一次使用 identifiers 列表时,
#不再需要 指定 name。但是如果你要使用多个,仍然要指定
name = PropertiesConfig
# 指定日志文件的位置和文件名称,以便记录多份日志时,直接引用
property.filename = E:/target/logs

# 级别过滤(过滤日志记录)
filter.threshold.type = ThresholdFilter
# 只记录debug级别以上的日志,大小写无关:(ALL<)TRACE<DEBUG<INFO<WARN<ERROR<FATAL(<OFF)
filter.threshold.level = debug

# 控制台类型的日志输出源
appender.console.type = Console
# 输出源的名称
appender.console.name = STDOUT
# 输出布局类型
appender.console.layout.type = PatternLayout
# 控制台输出编码
appender.console.layout.charset=UTF-8
# 输出模板
appender.console.layout.pattern =%d %p %C{1.} [%t] %m%n
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = debug

# 文件滚动记录类型的日志输出源
appender.rolling.type = RollingFile
# 指定当前滚动输出源的名称
appender.rolling.name = RollingFile
# 指定当前日志文件的位置和文件名称,可以单独指定,也可以直接引用之前定义过得property.filename参数
appender.rolling.fileName = ${filename}/findit.log
# 指定当发生Rolling时,文件的转移和重命名规则
appender.rolling.filePattern = ${filename}/findit-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
# 滚动记录输出源布局类型
appender.rolling.layout.type = PatternLayout
# 日志文件输出编码
appender.rolling.layout.charset=UTF-8
# 滚动记录输出模板
appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n
# 指定记录文件的封存策略,该策略主要是完成周期性的日志文件封存工作
appender.rolling.policies.type = Policies
# 基于时间的触发策略(TriggeringPolicy)
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
# 当前记录周期为每2秒生成一个文件,如果filePattern中配置的文件重命名规则是target/rolling2/test1-%d{yyyy-MM-dd HH-mm}-%i,最小的时间粒度是mm,即分钟,TimeBasedTriggeringPolicy指定的size是1,结合起来就是每2分钟生成一个新文件。如果改成%d{yyyy-MM-dd HH},最小粒度为小时,则每2个小时生成一个文件。
appender.rolling.policies.time.interval = 2
# 是否对封存时间进行调制。若modulate=true,则封存时间将以0点为边界进行偏移计算。比如,modulate=true,interval=4hours,那么假设上次封存日志的时间为03:00,则下次封存日志的时间为04:00,之后的封存时间依次为08:00,12:00,16:00
appender.rolling.policies.time.modulate = true
# 基于日志文件体积的触发策略。
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
# 当日志文件体积大于size指定的值时,触发Rolling
appender.rolling.policies.size.size=100MB
# 文件封存的覆盖策略(RolloverStrategy)
appender.rolling.strategy.type = DefaultRolloverStrategy
# 生成分割(封存)文件的个数,默认为5(-1,-2,-3,-4,-5)
appender.rolling.strategy.max = 5
# 设置字符集编码
appender.rolling.Encoding=UTF-8

# 记录器名称
logger.rolling.name = com.example.my.app
# 设置打印级别(日志级别)
logger.rolling.level = debug
# 是否向上级logger传递打印信息
logger.rolling.additivity = false
# 关联名称为RollingFile的输出源(appender)
logger.rolling.appenderRef.rolling.ref = RollingFile

# 根记录器,所有记录器的父辈
rootLogger.level = info
# 关联名称为STDOUT的输出源(appender)
rootLogger.appenderRef.stdout.ref = STDOUT
# 关联名称为RollingFile的输出源(appender)
rootLogger.appenderRef.rolling.ref = RollingFile

5、 Web容器初始化 配置

package com.cogitationsoft.findit.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * @author: Andy
 * @date: 5/2/2018 11:34 AM
 * @description: BaseConfig WebApplicationInitializer
 * @version: 1.0
 */
public class ApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {



    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

6、 根配置信息

package com.cogitationsoft.findit.config;

import org.springframework.context.annotation.*;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.regex.Pattern;

/**
 * @author: Andy
 * @date: 5/3/2018 5:11 PM
 * @description: 根配置信息, 用于加载SpringIoc Context
 * @version: 1.0
 */
@Configuration
@ComponentScan(basePackages = {"com.cogitationsoft.findit"}, excludeFilters = {
        @ComponentScan.Filter(type = FilterType.CUSTOM, value = RootConfig.WebPackage.class)
})
@EnableTransactionManagement
@PropertySource("classpath:log4j2.properties")
@Import(MyBatisConfig.class)
public class RootConfig{
    // 内部类,用来排除 web 相关的包,因为这些包已经在 WebConfig 中导入了
    public static class WebPackage extends RegexPatternTypeFilter {
        public WebPackage() {
            super(Pattern.compile("org\\.acherie\\.web"));
        }
    }
}

7、SpringMvc配置

 package com.cogitationsoft.findit.config;        
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.ViewResolver;
    import org.springframework.web.servlet.config.annotation.*;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
    import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
    
    /**
     * @author: Andy
     * @date: 5/2/2018 2:20 PM
     * @description: SpringMVC starter
     * @version: 1.0
     */
    @Configuration
    @EnableWebMvc
    @ComponentScan("com.cogitationsoft.findit")
    public class WebConfig extends WebMvcConfigurerAdapter{
    
        /**
         * Method Description:
         * 〈配置视图解析器〉
         *
         * @param:      null
         * @return:     ViewResolver
         * @author:     Andy
         * @date:       5/3/2018 4:05 PM
         */
        @Bean
        public ViewResolver viewResolver(){
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/views/");
            resolver.setSuffix(".ftl");
            resolver.setExposeContextBeansAsAttributes(true);
            return resolver;
        }
    
        /**
         * Method Description:
         * 〈配置Freemarker〉
         *
         * @param:      null
         * @return:
         * @author:     Andy
         * @date:       5/3/2018 4:07 PM
         */
        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            registry.enableContentNegotiation(new MappingJackson2JsonView());
            registry.freeMarker().cache(false);
        }
        @Bean
        public FreeMarkerConfigurer freeMarkerConfigurer() {
            FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
            configurer.setTemplateLoaderPath("/WEB-INF/views/");
            return configurer;
        }
    
        /**
         * Method Description:
         * 〈静态资源位置〉
         *
         * @param:      ResourceHandlerRegistry 静态资源处理器注册
         * @return:     void
         * @author:     Andy
         * @date:       5/3/2018 4:45 PM
         */
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/resources/**").addResourceLocations("/public-resources/");
        }        
    }

8、 Mybatis 及 druid基本配置

package com.cogitationsoft.findit.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author: Andy
 * @date: 5/3/2018 5:57 PM
 * @description: Mybatis 配置信息
 * @version: 1.0
 */
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:config/druid.properties")
@MapperScan("com.cogitationsoft.findit.mapper")
public class MyBatisConfig {
    @Autowired(required = false)
    public Environment env;

    @Value("${druid.driverClassName}")
    private String driver;

    @Value("${druid.url}")
    private String url;

    @Value("${druid.username}")
    private String username;

    @Value("${druid.password}")
    private String password;

    @Value("${druid.initialSize}")
    private int initialSize;

    @Value("${druid.minIdle}")
    private int minIdle;

    @Value("${druid.maxActive}")
    private int maxActive;

    @Value("${druid.maxWait}")
    private int maxWait;

    @Value("${druid.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${druid.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Bean(initMethod = "init", destroyMethod = "close")
    public DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        // 基本属性 url、user、password
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        // 配置初始化大小、最小、最大
        dataSource.setInitialSize(initialSize);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxActive(maxActive);

        // 配置获取连接等待超时的时间
        dataSource.setMaxWait(maxWait);

        // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

        // 配置一个连接在池中最小生存的时间,单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

        dataSource.setValidationQuery("SELECT 'X'");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);

        // 是否打开PSCache,并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(false);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(ApplicationContext applicationContext) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        // 设置 mapper xml
        //sessionFactory.setMapperLocations(applicationContext.getResources("classpath:mapper/**/*.xml"));
        return sessionFactory.getObject();
    }

    @Bean
    public PlatformTransactionManager txManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}

9、 基于druid和jdbc配置的属性文件(数据库应用的是mysql)

druid.driverClassName=com.mysql.jdbc.Driver
druid.url=jdbc:mysql://127.0.0.1:3306/db_findit?useUnicode=true&characterEncoding=UTF-8&useSSL=false
druid.username=root
druid.password=root
druid.initialSize=10
druid.minIdle=6
druid.maxActive=50
druid.maxWait=60000
druid.timeBetweenEvictionRunsMillis=60000
druid.minEvictableIdleTimeMillis=300000
druid.validationQuery=SELECT 'x'
druid.testWhileIdle=true
druid.testOnBorrow=false
druid.testOnReturn=false
druid.poolPreparedStatements=false
druid.maxPoolPreparedStatementPerConnectionSize=20
druid.filters=wall,stat

10、mapper.xml文件

说明:这里使用的是xml好像并不符合全配置的本意,但是在mabatis使用的灵活性上来看,如果使用注解的形式并不合适。并且官方也不建议使用javaConfig的形式,况且用java直接写sql也并不是什么优雅的事,虽然官方提供了sqlbuilder, 我还是认为这是一件很愚蠢的事。

<?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="com.cogitationsoft.findit.mapper.DemoMapper">
    <insert id="insert" parameterType="com.cogitationsoft.findit.pojo.DemoDO">
        insert into t_demo (id, no, name)
        values (#{id}, #{no}, #{name})
    </insert>
</mapper>
这里只用了一个插入的方法。




关于配置的东西到这里其实就完成了,才疏学浅,如果有大神看见问题还请指正。下面是github的链接, 可以看完整的代码。
https://github.com/WHXGIT/demo

clipboard.png
因同步时出现问题, 请把所有文件放入到findIt文件夹下用idea打开项目。


Andy
54 声望11 粉丝

Remember,Hope is a good thing,maybe the best of things and no good thing ever dies!