maven创建多模块化项目(三)

1.上篇https://www.cnblogs.com/fishyy/p/10315473.html配置了mybaits-config.xml文件,但是并未使用,这里简单使用下。

2.并不建议所有bean全部配置在一个applicationContext.xml文件中,而是各个模块管理自身需要使用的bean,最后统一由web层的ContextLoaderListener加载。

在appcms-dao中新建resources资源文件夹,并添加applicationContext-dao.xml文件

将之前写在appcms-web层applicationContext.xml文件中关于数据访问的相关bean剪切到appcms-dao层的applicationContext-dao.xml

applicationContext-dao.xml内容如下

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    <!-- 数据源 -->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="yyu010383" />
    </bean>

    <!-- 配置session工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置AOP通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置事务属性 -->
        <tx:attributes>
            <!-- 添加事务管理的方法 -->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="select*" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置AOP,为添加事务管理的操作配置AOP -->
    <aop:config>
        <!-- 引入的Spring定义的事务通知,需要使用aop:advisor -->
        <!-- 下面难 -->
        <aop:advisor advice-ref="txAdvice"
                     pointcut="execution(* com.yyu.cms.service.*.*(..))"
        />
    </aop:config>
</beans>
View Code

其中mybatis-config.xml报红,当然是要把之前放在appcms-web模块中的mybatis-config.xml剪切到appcms-dao层

最后一步是修改web.xml文件,将applicationContext-dao.xml文件交给ContextLoaderListener加载。

至此,将mybatis等数据库访问相关内容转移到了appcms-dao层。

3.创建test数据库,并新建tb_user表。

CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `test`;

CREATE TABLE IF NOT EXISTS `tb_user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL DEFAULT '',
  `password` varchar(32) NOT NULL DEFAULT '',
  `email` varchar(32) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

DELETE FROM `tb_user`;
/*!40000 ALTER TABLE `tb_user` DISABLE KEYS */;
INSERT INTO `tb_user` (`id`, `name`, `password`, `email`) VALUES
    (1, 'yyu', '123456', 'foreveryuya@foxmail.com');
View Code

4.在appcms-domain pom.xml中加入dependency,解决实体类名,字段名与表名,列名不一致的问题。

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

  <parent>
    <groupId>com.yyu.cms</groupId>
    <artifactId>appcms</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <groupId>com.yyu.cms.domain</groupId>
  <artifactId>appcms-domain</artifactId>
  <packaging>jar</packaging>
  <name>appcms-domain</name>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.persistence</groupId>
      <artifactId>persistence-api</artifactId>
      <version>1.0</version>
    </dependency>
  </dependencies>
</project>
View Code

新建User类

User.java

package com.yyu.cms.domain.po;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Table(name = "tb_user")
public class User implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private String password;

    private String email;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
View Code

5.在appcms-dao中,使用通用mapper,在appcms-dao pom.xml中加入

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

  <parent>
    <groupId>com.yyu.cms</groupId>
    <artifactId>appcms</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <groupId>com.yyu.cms.dao</groupId>
  <artifactId>appcms-dao</artifactId>
  <packaging>jar</packaging>
  <name>appcms-dao</name>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.yyu.cms.common</groupId>
      <artifactId>appcms-common</artifactId>
      <version>${app.version}</version>
    </dependency>
    <dependency>
      <groupId>com.yyu.cms.domain</groupId>
      <artifactId>appcms-domain</artifactId>
      <version>${app.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!-- 通用Mapper -->
    <dependency>
      <groupId>tk.mybatis</groupId>
      <artifactId>mapper</artifactId>
      <version>3.3.8</version>
    </dependency>
  </dependencies>
</project>
View Code

新建如下图类

BaseMapper.java

package com.yyu.cms.dao;

import tk.mybatis.mapper.common.Mapper;

/**
 * Mapper接口:基本的增、删、改、查方法
 * @param <T>
 */
public interface BaseMapper<T> extends Mapper<T> {

}
View Code

UserMapper.java

package com.yyu.cms.dao.mapper;

import com.yyu.cms.dao.BaseMapper;
import com.yyu.cms.domain.po.User;

public interface UserMapper extends BaseMapper<User>{

}
View Code

在applicationContext-dao.xml中配置通用Mapper

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:component-scan base-package="com.yyu.cms.dao.mapper"/>

    <!-- 数据源 -->
    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="yyu010383" />
    </bean>

    <!-- 配置session工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 文件映射器,指定类文件 -->
        <property name="configLocation" value="classpath:/mybatis-config.xml"/>
        <!-- 自动扫描mapping.xml文件 -->
        <!--<property name="mapperLocations" value="classpath:*.xml" />-->
    </bean>

    <!-- 通用mapper -->
    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.yyu.cms.dao.mapper" />
        <property name="properties">
            <value>
                mappers=tk.mybatis.mapper.common.Mapper
            </value>
        </property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置AOP通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置事务属性 -->
        <tx:attributes>
            <!-- 添加事务管理的方法 -->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="select*" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置AOP,为添加事务管理的操作配置AOP -->
    <aop:config>
        <!-- 引入的Spring定义的事务通知,需要使用aop:advisor -->
        <!-- 下面难 -->
        <aop:advisor advice-ref="txAdvice"
                     pointcut="execution(* com.yyu.cms.service.*.*(..))"
        />
    </aop:config>
</beans>
View Code

修改mybaits-config.xml文件,设置实体类扫描路径为com.yyu.cms.domain.po

<?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>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 设置包扫描(别名) -->
    <typeAliases>
        <package name="com.yyu.cms.domain.po"/>
    </typeAliases>
    <!-- 配置环境:可以配置多个环境,default:配置某一个环境的唯一标识,表示默认使用哪个环境 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!-- 配置连接信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/test"/>
                <property name="username" value="root"/>
                <property name="password" value="yyu010383"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 配置映射文件:用来配置sql语句和结果集类型等 -->
    <mappers>
        <!--<mapper resource="mapper/UserMapper.xml"/>-->
    </mappers>
</configuration>
View Code

6.在appcms-service中新建UserService和UerServiceImpl

UserService.java

package com.yyu.cms.service;

import com.yyu.cms.domain.po.User;

import java.util.List;

public interface UserService {
    boolean add(User user);

    List<User> list();
}
View Code

UerServiceImpl.java

package com.yyu.cms.service.impl;

import com.yyu.cms.dao.mapper.UserMapper;
import com.yyu.cms.domain.po.User;
import com.yyu.cms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    public boolean add(User user) {
        return userMapper.insert(user) > 0 ? true : false;
    }

    public List<User> list() {
        return userMapper.selectByExample(null);
    }
}
View Code

7.在appcms-web新建UserController

UserController.java

package com.yyu.cms.web.controller;

import com.yyu.cms.domain.po.User;
import com.yyu.cms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public boolean add(@RequestBody User user) {
        return userService.add(user);
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<User> list() {
        return userService.list();
    }
}
View Code

8.如果此时访问http://localhost:8080/user/list,会报No converter found for return value of type: class java.util.ArrayList 访问http://localhost:8080/user/add会报HTTP Status 415 – Unsupported Media Type,

这是由于springmvc没有内置json处理框架,这里添加fastjson

在父pom.xml中加入

在appcms-web pom.xml中加入

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

  <parent>
    <groupId>com.yyu.cms</groupId>
    <artifactId>appcms</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <groupId>com.yyu.cms.web</groupId>
  <artifactId>appcms-web</artifactId>
  <packaging>war</packaging>
  <name>appcms-web Maven Webapp</name>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.yyu.cms.service</groupId>
      <artifactId>appcms-service</artifactId>
      <version>${app.version}</version>
    </dependency>
    <!-- spring mvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
    </dependency>
  </dependencies>

  <build>
    <finalName>appcms-web</finalName>
  </build>
</project>
View Code

 同时修改my-dispatcher-servlet.xml注入fastjson http消息转换器

<?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"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 扫描web层的bean -->
    <context:component-scan base-package="com.yyu.cms.web.controller"/>

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 解决Controller返回中文字符串乱码问题 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <!-- 添加json处理框架 -->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                        <value>application/xml;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>
View Code

9.使用postman再次访问

查看数据库

 欢迎star github https://github.com/foreveryuya/appcms

posted @ 2019-01-25 11:26  fishyy  阅读(488)  评论(0编辑  收藏  举报