基于java配置的SSM框架详细整合

2017-08-03  本文已影响0人  鉴闻俗说

一、整合Spring MVC + mybatis

1、配置DispatcherServlet

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

/**
 * 扩展AbstractAnnotationConfigDispatcherServletInitializer的任意类都会自动地配置
 * DispatcherServlet和Spring应用上下文,Spring的应用上下文会位于应用程序的Servlet上下文之中
 */
public class MpdidbWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer
{
    /**
     *返回带有@Configuration注解的类将会用来配置ContextLoaderListener创建应用的应用上下文中的bean。
     * ContextLoaderListener要加载应用中的其他bean,这些bean通常是驱动应用后端的中间层和数据层的组件。
     */
    @Override
    protected Class<?>[] getRootConfigClasses()
    {
        return new Class<?>[] {RootConfig.class};
    }

    /**
     *返回带有@Configuration注解的类将会用来定义DispatcherServlet应用上下文中的bean。
     * DispatcherServlet加载包含Web组件的bean,如控制器、视图解析器以及处理器映射器。
     */
    @Override
    protected Class<?>[] getServletConfigClasses()
    {
        return new Class<?>[] {WebConfig.class};
    }

    /**
     * 将一个或多个路径映射到DispatcherServlet上,
     * 此处它的映射是“/”,即默认的Servlet,会处理进入应用的所有请求
     */
    @Override
    protected String[] getServletMappings()
    {
        return new String[] { "/" };
    }
}

2、启用Spring MVC

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.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc   //启用Spring MVC
@ComponentScan("com.mpdidb.controller")  //启用组件扫描
public class WebConfig extends WebMvcConfigurerAdapter
{
    //配置JSP视图解析器
    @Bean
    public ViewResolver viewResolver()
    {
        InternalResourceViewResolver resolver =
                new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        //可以在JSP页面中通过${}访问beans
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }
    /**
     * WebConfig类扩展了configurer WebMvcConfigurerAdapter并重写了其configureDefaultServletHandling()方法.
     * 通过调用DefaultServletHandlerConfigurer的enable()方法,要求DispatcherServlet将对静态资源的请求转发到Servlet容器默认的
     * Servlet上,而不是使用DispatcherServlet来处理此类请求。
     * @param
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
    {
        configurer.enable();
    }
}

3、创建RootConfig配置类

WebConfig配置类已经就绪,下面创建RootConfig配置类。该配置类中导入了DataConfig配置类,DataConfig配置类整合了spring+mybatis

import org.springframework.context.annotation.*;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@Import(DataConfig.class)
/**
 * 设置扫描机制的时候,将之前WebConfig设置过的那个包排除了;
 */
@ComponentScan(basePackages = {"com.mpdidb"},
    excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,
            value = EnableWebMvc.class)})
public class RootConfig
{
}

4、创建DataConfig配置类

mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mpdidb?useUnicode=true&characterEncoding=utf-8&useSSL=false&zeroDateTimeBehavior=convertToNull&autoReconnect=true
mysql.username=Your_username
mysql.password=Your_password
import org.apache.commons.dbcp.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
//使用@MapperScan来扫描注册mybatis数据库接口类,其中basePackages属性表明接口类所在的包
@MapperScan(basePackages = "com.mpdidb.mapper")
@PropertySource("classpath:jdbc.properties")
public class DataConfig
{
    @Autowired
    private Environment environment;

    /**
     * 使用数据库链接池配置数据源
     */
    @Bean
    public BasicDataSource dataSource()
    {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(environment.getProperty("mysql.driver"));
        ds.setUrl(environment.getProperty("mysql.url"));
        ds.setUsername(environment.getProperty("mysql.username"));
        ds.setPassword(environment.getProperty("mysql.password"));
        //初始化连接大小
        ds.setInitialSize(5);
        //初始化连接池数量
        ds.setMaxActive(10);
        return ds;
    }

    /**
     * 声明mybatis的session工厂
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws Exception
    {
        ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.mpdidb.domain");
        sqlSessionFactoryBean.setMapperLocations(patternResolver.getResources("classpath:mapping/*Mapper.xml"));
        return sqlSessionFactoryBean;
    }
}

二、测试

1、测试前需要的文件

2017-08-03 11-31-25屏幕截图.png
public class TbUser {
    private String userId;

    private String userRole;

    private String userName;

    private String password;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId == null ? null : userId.trim();
    }

    public String getUserRole() {
        return userRole;
    }

    public void setUserRole(String userRole) {
        this.userRole = userRole == null ? null : userRole.trim();
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    @Override
    public String toString() {
        return "TbUser{" +
                "userId='" + userId + '\'' +
                ", userRole='" + userRole + '\'' +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

<?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.mpdidb.mapper.TbUserMapper">
  <resultMap id="BaseResultMap" type="com.mpdidb.domain.TbUser">
    <id column="user_id" jdbcType="VARCHAR" property="userId" />
    <result column="user_role" jdbcType="VARCHAR" property="userRole" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="password" jdbcType="VARCHAR" property="password" />
  </resultMap>


  <select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
    select *
    from tb_user
    where user_id = #{userId,jdbcType=VARCHAR}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.String">
    delete from tb_user
    where user_id = #{userId,jdbcType=VARCHAR}
  </delete>

  <insert id="insert" parameterType="com.mpdidb.domain.TbUser">
    insert into tb_user (user_id, user_role, user_name, 
      password)
    values (#{userId,jdbcType=VARCHAR}, #{userRole,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, 
      #{password,jdbcType=VARCHAR})
  </insert>

  <update id="updateByPrimaryKey" parameterType="com.mpdidb.domain.TbUser">
    update tb_user
      set user_role = #{userRole,jdbcType=VARCHAR},
      user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR}
      where user_id = #{userId,jdbcType=VARCHAR}
  </update>
</mapper>
import com.mpdidb.domain.TbUser;

import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

@Repository
public interface TbUserMapper {


    int deleteByPrimaryKey(String userId);

    int insert(TbUser record);

    TbUser selectByPrimaryKey(String userId);

    int updateByPrimaryKey(TbUser record);
}
import com.mpdidb.domain.TbUser;

public interface TbUserService
{
    TbUser selectByPrimaryKey(String userId);
}
import com.mpdidb.domain.TbUser;
import com.mpdidb.mapper.TbUserMapper;
import com.mpdidb.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TbUserServiceImpl implements TbUserService
{
    @Autowired
    private TbUserMapper tbUserMapper;

    @Override
    public TbUser selectByPrimaryKey(String userId)
    {
        return tbUserMapper.selectByPrimaryKey(userId);
    }
}

2、编写测试类

import com.mpdidb.config.RootConfig;
import com.mpdidb.domain.TbUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class) //让测试运行于spring测试环境,在使用所有注释前必须使用
@ContextConfiguration(classes = {RootConfig.class})
public class TbUserServiceTest
{
    @Autowired
    private TbUserService tbUserService;


    @Test
    public void selectByPrimaryKeyTest()
    {
        String userId = "wusuodai";
        TbUser tbUser = tbUserService.selectByPrimaryKey(userId);
        System.out.println(tbUser.getUserName());
    }

}

3、测试结果,通过

2017-08-03 11-43-33屏幕截图.png
上一篇下一篇

猜你喜欢

热点阅读