SSM框架整合实战:从零开始学习SSM整合配置

SSM框架是指Spring、SpringMVC和MyBatis的整合,是Java开发中常用的轻量级框架。通过SSM框架,我们能快速搭建起一个强大的Web应用,具备良好的可维护性和扩展性。本文将详细介绍如何从零开始学习SSM框架的整合配置,并给出具体的代码示例。

一、项目结构

在开始整合之前,我们先建立一个基本的Maven项目,其结构如下所示:

ssm-demo
│
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           ├── config
│   │   │           ├── controller
│   │   │           ├── dao
│   │   │           ├── service
│   │   │           └── model
│   │   └── resources
│   │       ├── mapper
│   │       ├── applicationContext.xml
│   │       ├── spring-mvc.xml
│   │       └── mybatis-config.xml
│   └── test
└── pom.xml

二、Maven依赖

pom.xml中,我们需要添加Spring、SpringMVC和MyBatis的相关依赖:

<dependencies>
    <!-- Spring框架相关 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.13</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.13</version>
    </dependency>

    <!-- MyBatis相关 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>

    <!-- 其他依赖 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
</dependencies>

三、Spring配置

applicationContext.xml中,我们配置Spring的核心内容:

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

    <context:component-scan base-package="com.example" />
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/testdb" />
        <property name="username" value="root" />
        <property name="password" value="password" />
    </bean>

    <bean id="sqlSessionFactory" class="org.apache.ibatis.session.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory" />
    </bean>

</beans>

四、Spring MVC配置

spring-mvc.xml中配置SpringMVC的相关内容:

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

    <mvc:annotation-driven />
    <mvc:component-scan base-package="com.example.controller" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

五、MyBatis配置

mybatis-config.xml中进行MyBatis的基本配置:

<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

六、Controller、Service、Repository

接下来我们编写简单的CRUD接口,先定义一个User模型:

package com.example.model;

public class User {
    private int id;
    private String name;
    // Getters and Setters
}

然后是UserMapper接口:

package com.example.dao;

import com.example.model.User;

public interface UserMapper {
    void insertUser(User user);
    User getUserById(int id);
    void updateUser(User user);
    void deleteUser(int id);
}

再是UserService服务层:

package com.example.service;

import com.example.dao.UserMapper;
import com.example.model.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    private final UserMapper userMapper;

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Transactional
    public void saveUser(User user) {
        userMapper.insertUser(user);
    }

    public User findUserById(int id) {
        return userMapper.getUserById(id);
    }
}

最后是Controller层:

package com.example.controller;

import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

    @PostMapping
    public String addUser(@RequestBody User user) {
        userService.saveUser(user);
        return "User added successfully!";
    }

    @GetMapping("/{id}")
    public User getUser(@PathVariable int id) {
        return userService.findUserById(id);
    }
}

结语

通过以上步骤,我们成功搭建了一个简单的SSM框架示例。SSM结合了Spring的强大功能和MyBatis的灵活性,使得我们的开发变得更加高效和便捷。后续可以在此基础上添加更多功能,如异常处理、日志记录等,进一步提升系统的健壮性和用户体验。希望通过本文的介绍,你能够更好地理解和运用SSM框架进行项目开发。

点赞(0) 打赏

微信小程序

微信扫一扫体验

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部