SSM框架整合的简单示例(注解版)

参考链接:SSM框架整合的简单示例(XML版)

1、数据库表

创建一个简单的数据库及t_book表,包含几个简单字段能够演示即可

CREATE DATABASE `ssm`;

CREATE TABLE `t_book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `bname` varchar(32) DEFAULT NULL,
  `bcount` int(11) DEFAULT NULL,
  `descript` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8

2、创建工程

  • 新建一个普通的maven工程,不需要选模板,原始的maven工程

  • 导入相关依赖

    <!--数据库连接相关-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.49</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.5</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.3.3</version>
    </dependency>
    
    <!--数据相关,JSON-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.75</version>
    </dependency>
    
    <!--Mybatis相关-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.6</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.6</version>
    </dependency>
    
    <!--SpringMVC相关-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.3</version>
    </dependency>
    
    <!--Web相关-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    
    <!--日志相关-->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.3.0-alpha5</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.25</version>
    </dependency>
    
    <!--单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13</version>
      <scope>test</scope>
    </dependency>
    

3、三层框架的基本实现

3.1、实体类

Book.java

package com.yusian.entity;

public class Book {
    private Integer id;
    private String bname;
    private Integer bcount;

    public Integer getId() {
        return id;
    }

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

    public String getBname() {
        return bname;
    }

    public void setBname(String bname) {
        this.bname = bname;
    }

    public Integer getBcount() {
        return bcount;
    }

    public void setBcount(Integer bcount) {
        this.bcount = bcount;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", bname='" + bname + '\'' +
                ", bcount=" + bcount +
                '}';
    }
}

mysql.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://node.yusian.net/ssm?useSSL=false
username = root
password = Root@123

MysqlConfig.java

  • 这是Mysql的配置文件,将可变参数从代码中分离出来
  • @Repository注解自动生成bean
  • @PropertySource加载配置文件
  • @Value注解自动赋值
package com.yusian.entity;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Repository;

@Repository
@PropertySource("classpath:mysql.properties")
public class MysqlConfig {
    @Value("${driver}")
    private String driver;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

3.2、Dao层

BookDao.java

  • @Select注解能自动生成对应的Mapper中的数据库相关操作
package com.yusian.dao;

import com.yusian.entity.Book;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface BookDao {
    @Select("select * from t_book")
    List<Book> findAll();
}

3.3、Service层

BookService.java

package com.yusian.service;

import com.yusian.entity.Book;

import java.util.List;

public interface BookService {
    List<Book> findAll();
}

BookServiceImpl.java

  • @Service注解其本质是Component注解,Spring创建bean对象
  • @Autowired注解将Spring创建的bean自动装配
package com.yusian.service.impl;

import com.yusian.dao.BookDao;
import com.yusian.entity.Book;
import com.yusian.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("bookService")
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    public List<Book> findAll() {
        return bookDao.findAll();
    }

    public BookDao getBookDao() {
        return bookDao;
    }

    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }
}

4、Spring整合Mybatis

AppConfig.java

  • @Configuration
package com.yusian.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.yusian.entity.MysqlConfig;
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.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@ComponentScan({"com.yusian.entity", "com.yusian.service.impl", "com.yusian.controller"})
@MapperScan("com.yusian.dao")
public class AppConfig {

    @Autowired
    private MysqlConfig config;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(config.getDriver());
        dataSource.setUrl(config.getUrl());
        dataSource.setUsername(config.getUsername());
        dataSource.setPassword(config.getPassword());
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.yusian.entity");
        return bean;
    }
}

5、单元测试

package com.yusian;

import com.yusian.entity.Book;
import com.yusian.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.List;

public class AnnotationTest {

    @Test
    public void serviceTest() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext("com.yusian.config");
        BookService bookService = (BookService) ctx.getBean("bookService");
        List<Book> books = bookService.findAll();
        for (Book book : books) {
            System.out.println("book = " + book);
        }
    }
}

运行结果:

book = Book{id=1, bname='西游记', bcount='10'}
book = Book{id=2, bname='三国演义', bcount='20'}
book = Book{id=3, bname='水浒传', bcount='30'}
book = Book{id=4, bname='红楼梦', bcount='40'}

Process finished with exit code 0

6、SpringMVC整合Web应用

6.1、基础配置

  • 将当前Module转换为Web项目:Add Framework Support,勾选Web Application
  • web.xml中配置servlet,由DispatcherServlet统一接管请求
  • Spring配置默认指向springmvc-servlet.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_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Springmvc-servlet.xml

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

    <context:component-scan base-package="com.yusian.config"/>

</beans>

6.2、编写控制器

BookController.java

package com.yusian.controller;

import com.alibaba.fastjson.JSON;
import com.yusian.entity.Book;
import com.yusian.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class BookController {

    @GetMapping(value = "/book", produces = "application/json;charset=utf8")
    public String findAll() {
        ApplicationContext ctx = new AnnotationConfigApplicationContext("com.yusian.config");
        BookService bookService = (BookService) ctx.getBean("bookService");
        List<Book> books = bookService.findAll();
        return JSON.toJSONString(books);
    }
}

6.3、测试

浏览器中访问http://localhost:8080/book即可看到查询出来的图书列表Json字符串

SSM框架整合的简单示例(注解版)》有1个想法

  1. Pingback引用通告: SSM框架整合的简单示例(XML版) | 年年有"余"

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注