Spring的快速入门
1、什么是Spring?
Spring实质上就是一个容器,用来管理bean(对象),这些bean包括service层、dao层里面的所有对象、Mybatis的SqlSessionFactoryBean对象以及数据源连接池对象,这些都归Spring来进行管理
2、快速搭建一个简单案例,帮助大家理解Spring
一、 在pom.xml文件中导入相关的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.zyyx</groupId>
<artifactId>springdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 依赖的管理 -->
<dependencies>
<!-- 单元测试Junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!-- Mysql的连接依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- 引入druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>
<!-- 导入spring的context-support依赖,会自动引入spring的其它依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
<!-- 引入spring-jdbc的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
</dependencies>
</project>
二、 创建实体类Users、UserDao、UserService等类
1、实体类User
package cn.zyyx.domain;
public class User {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
2、Dao层的BaseDao和UserDaoImpl
package cn.zyyx.dao;
import java.util.List;
public interface BaseDao<T> {
void insert(T t);
void delete(Integer id);
void update(T t);
T selectOne(Integer id);
List<T> selectAll();
}
package cn.zyyx.dao.impl;
import cn.zyyx.dao.BaseDao;
import cn.zyyx.domain.User;
import cn.zyyx.util.Util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements BaseDao<User> {
/*
增加
*/
public void insert(User user) {
Connection connection = Util.getConnection();
String sql = "insert into users(name,age) values(?,?)";
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
ps.setString(1,user.getName());
ps.setInt(2,user.getAge());
ps.execute();
ps.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
删除
*/
public void delete(Integer id) {
Connection connection = Util.getConnection();
String sql = "delete from users where id = ?";
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
ps.setInt(1,id);
ps.execute();
ps.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void update(User user) {
Connection connection = Util.getConnection();
String sql = "update users set name = ? , age = ? wherre id = ?";
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
ps.setString(1,user.getName());
ps.setInt(2,user.getAge());
ps.setInt(3,user.getId());
ps.executeUpdate();
ps.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public User selectOne(Integer id) {
Connection connection = Util.getConnection();
String sql = "select * from users where id = ?";
PreparedStatement ps = null;
User user = null;
try {
ps = connection.prepareStatement(sql);
ps.setInt(1,id);
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()){
user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setAge(resultSet.getInt("age"));
}
ps.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
public List<User> selectAll() {
Connection connection = Util.getConnection();
String sql = "select * from users";
PreparedStatement ps = null;
List<User> userList = new ArrayList<User>();
try {
ps = connection.prepareStatement(sql);
ResultSet resultSet = ps.executeQuery();
while (resultSet.next()){
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setAge(resultSet.getInt("age"));
userList.add(user);
}
ps.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return userList;
}
}
3、Service层的UserService类
package cn.zyyx.service;
import cn.zyyx.dao.BaseDao;
import cn.zyyx.domain.User;
public class UserService {
private BaseDao<User> userDao;
public void setUserDao(BaseDao<User> userDao) {
this.userDao = userDao;
}
public BaseDao<User> getUserDao(){
return userDao;
}
}
4、工具类Util
package cn.zyyx.util;
import java.sql.Connection;
import java.sql.SQLException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
public class Util {
public static Connection getConnection() {
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
DataSource dataSource = (DataSource) ac.getBean("dataSource");
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
三、 在resources资源文件夹下创建Spring的核心配置文件beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置Druid连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!-- 驱动 -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!-- url -->
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<!-- 用户名 -->
<property name="username" value="root"/>
<!-- 密码 --。
<property name="password" value="root"/>
<!-- 最大连接数 -->
<property name="maxActive" value="10"/>
<!-- 最小连接数 -->
<property name="minIdle" value="2"/>
<!-- 初始化连接数 -->
<property name="initialSize" value="3"/>
</bean>
<!-- 对dao层的bean进行管理 -->
<bean id="userDao" class="cn.zyyx.dao.impl.UserDaoImpl"/>
<!-- 对service层的bean进行管理 -->
<bean id="userService" class="cn.zyyx.service.UserService">
<!-- 将userDao注入到userSerice里面 -->
<property name="userDao" ref="userDao"/>
</bean>
</beans>
四、 创建一个测试类进行单元测试
package cn.zyyx.test;
import cn.zyyx.dao.BaseDao;
import cn.zyyx.domain.User;
import cn.zyyx.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
public void testSpring(){
//获得Spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
//获取UserService对象
UserService userService = (UserService) ac.getBean("userService");
//调用方法获取UserDao
BaseDao<User> userDao = userService.getUserDao();
//执行查询语句并且返回结果
System.out.println(userDao.selectOne(9));
}
}
测试结果为
我的users表
五、 总结
Spring的本质就是对很多bean(即对象)进行管理,从beans.xml文件(可以看作为Spring容器)中,我们明显看出,Spring管理了数据源、UserDaoImpl以及UserService三个bean,这就是控制反转(IOC),并且将UserDaoImpl的bean赋给UserSerivce的属性,同时体现了依赖注入DI。从另一个角度来讲,IOC和DI本质上时同一个概念,只不过是从不同的角度来描述问题罢了。本人水平有限,希望能够帮助初学者了解到Spring的核心思想。
六、 代码
链接:https://pan.baidu.com/s/1axAFq6wyU6YYJJ0dPhxJPA
提取码:dzq5