使用纯JavaConfig配置spring 4和 spring data jpa

创建项目

长期以来,我都使用IDEA开发项目,所以教程是基于IDEA的操作来说的。

  1. 首先,在IDEA中建立一个Web Application的项目。

毫无疑问这里的两个前提是,你需要有JDK,并且在本地配置了Tomcat,才能继续。

建立项目
  1. 当建立完成项目之后,IDEA会自动做一些生成操作,包括了一个基础的java web代码结构。
image.png
  1. 接下来需要在其中引入需要的Spring的maven依赖。右击左上角的项目名称,点击Add Framework Support,在其中选择Maven并确认。
添加maven
勾选Maven

当Maven初始化完成,就可以开始添加依赖了,依赖包括了maven的编译插件以及Spring依赖和第三方常用依赖。

下面是我配置的Maven常用代码段,spring的版本是4.3.7.RELEASE,你可以在<spring.version>标签内替换成其他版本即可。

<properties>
        <spring.version>4.3.7.RELEASE</spring.version>
    </properties>
    <profiles>
        <profile>
            <id>jdk-1.8</id>
            <activation>
                <activeByDefault>true</activeByDefault>
                <jdk>1.8</jdk>
            </activation>
            <properties>
                <maven.compiler.source>1.8</maven.compiler.source>
                <maven.compiler.target>1.8</maven.compiler.target>
                <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
            </properties>
        </profile>
    </profiles>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--Spring-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <!--配置Spring Data-->
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>1.13.1.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.3.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据连接池-->
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <!--数据库驱动-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.8.Final</version>
        </dependency>
        <!--日志-->
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.8.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.8.1</version>
        </dependency>
        <!--JSON-->
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>
        <!--Apache 工具类-->
        <!--工具-->
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.6</version>
        </dependency>
    </dependencies>

等待所有的依赖进度加载完成,就可以开始配置Spring了。

Maven的速度可能会非常慢,需要的话自行百度阿里镜像

配置基础的结构

在Spring的官方文档和实例中,有一种抽象类叫做AbstractAnnotationConfigDispatcherServletInitializer这是用来配置web应用的初始化类,会在Spring web应用启动时先于用户配置被加载。其中提供了三个与Web应用配置有关的抽象方法,getRootConfigClassesgetServletConfigClassesgetServletMappings

这三个方法作用分别是:

  • getRootConfigClasses: 返回根上下文配置的类
  • getServletConfigClasses: 返回配置了web上下文的类
  • getServletMappings: 返回根ServletMapping的路径

所以在配置开始的时候,需要手写一个启动类继承AbstractAnnotationConfigDispatcherServletInitializer抽象类,并实现上述三个方法。这样在系统启动的时候,会自动加载指定的方法。

一般情况下,我使用一个RootConfiguration类表示根上下文,使用一个ServletConfiguration类表示web上下文。

编写启动类Bootstrap类如下:

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
 * Created by HMH on 2017/9/25.
 */
public class Bootstrap extends AbstractAnnotationConfigDispatcherServletInitializer {
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { RootConfiguration.class };
    }
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[] { ServletConfiguration.class };
    }
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }
}

在getRootConfigClasses方法中,你可以返回各种配置信息,包括配置数据库的类、配置安全的类、配置消息的类等等。

配置ServletConfiguration

ServletConfiguration类中,这里只做一个简单的例子,配置一个jsp解析的前后缀,这是为了返回页面的时候,不需要写千篇一律的前后缀,在该类中可以定义Json解析、内容协商等等一系列的配置项。几乎和请求、解析、返回等Servlet相关的内容都配置在这里。

@Configuration
//@ImportResource("classpath:dispatcher-servlet.xml")
@EnableWebMvc
@ComponentScan(
        basePackages = "cn.hhchat.configDemo",
        includeFilters = {
            @ComponentScan.Filter(Controller.class),
            @ComponentScan.Filter(ControllerAdvice.class)
        })
public class ServletConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        registry.viewResolver(viewResolver);
    }
}

其中,
@Configuration表示这是一个配置类;
@EnableWebMvc可以屏蔽@EnableAutoConfiguration,一般与WebMvcConfigurerAdapter联用;
@ComponentScan是自动装配的核心,其中定义了搜索的包路径,以及搜索的目标注解。

WebMvcConfigurerAdapter也是一个抽象类,实现了一些操作,允许用户重写或实现其中一些方法来定制Servlet。

这里只实现了configureViewResolvers,在mvc方法返回String的时候自动添加前后缀。

配置RootConfiguration / Spring Data

RootConfiguration中可以配置全局都用得到的一些配置,在平时练习的时候,我就直接在这里配置Spring Data。

Spring Data和Hibernate / Mybatis的比较这里不在意,所以直接讲配置的情况。这里的配置,我曾经卡了一个月的时间,在网上找了非常的多的资料 - - 他们都是抄的前篇一律。。。最终还是靠官方文档来解决。。。

这里需要配置3个部分,分别是:

  1. dataSource数据源
  2. entityManagerFactory实体工厂
  3. transactionManager事务管理器

其实这里的配置非常直接,对于hibernate也是这么配置的(毕竟spring data jpa 是对hibernate的封装。。),但我之前就卡在不知道使用什么实现类来配置这些内容。


@Configuration
@EnableJpaRepositories(basePackages = "cn.hhchat.configDemo")
@ComponentScan(basePackages = "cn.hhchat.configDemo",excludeFilters = {
        @ComponentScan.Filter(EnableWebMvc.class), @ComponentScan.Filter(Controller.class)
})
public class RootConfiguration {
    /**
     * 配置数据源
     */
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://**host**/**database**?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false");
        dataSource.setUser("**user**");
        dataSource.setPassword("**pass**");
        dataSource.setMinPoolSize(1);
        dataSource.setMaxPoolSize(30);
        dataSource.setInitialPoolSize(5);
        dataSource.setAcquireIncrement(2);
        return dataSource;
    }
    /**
     * 配置实体工厂
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
        entityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter);
        Properties properties = new Properties();
        properties.put("hibernate.format_sql", "true");
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.hbm2ddl.auto", "update");
        properties.put("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
        entityManagerFactoryBean.setJpaProperties(properties);
        entityManagerFactoryBean.setPackagesToScan("org.example.site");
        return entityManagerFactoryBean;
    }
    /**
     * 配置事务
     */
    @Bean
    public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(entityManagerFactory);
        return jpaTransactionManager;
    }
}

整个类的配置如上所示,挪用的话,需要修改数据库连接的地址、用户名、密码、和扫描的包

需要注意的地方是在配置ServletConfiguration/RootConfigurationComponentScan的时候,一定要定义的非常细致。
对于Servlet来说只要Controller相关的注解,而root要剔除Controller。
对于Repository来说要直接指定到包含Entity注解和Repository注解的包中,这样能够避免搜索过程可能被屏蔽。这个地方曾经坑了我两天。。

尝试启动

编写一些代码,在IDEA中将所有的依赖添加到lib文件夹中,保证运行时可以被获取到。

image.png

启动你的项目,测试一下吧。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,039评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,426评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,417评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,868评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,892评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,692评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,416评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,326评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,782评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,957评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,102评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,790评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,442评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,996评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,113评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,332评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,044评论 2 355

推荐阅读更多精彩内容