Spring-Study
转载于Kuang shen Spring study in bilibili,仅作为学习备份
1. 简介
spring理念:是现有的技术更加容易使用,本身是一个大杂烩。
- SSH:Struct2 + Spring + Hibernate
- SSM: SpringMVC + Spring + Mybatis
官网: https://spring.io/projects/spring-framework#overview
官方下载: https://repo.spring.io/release/org/springframework/spring/
GitHub: https://github.com/spring-projects/spring-framework
Spring Web MVC » 5.2.5.RELEASE
1 2 3 4 5 6 7 8 9 10 11 12
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.5.RELEASE</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.3.RELEASE</version> </dependency>
|
- spring是开源的免费的容器。
- spring是一个轻量级的,非入侵式的。
- 控制反转(IOC),面向切面编程 (AOP)。
- 支持事务处理,对框架整合的支持。
总结:spring是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架。
2.IOC理论
UserDao
UserDaoImp
UserSevice
UserServiceImp
在之前,用户的需求可能会影响原来的代码。
使用一个set。
1 2 3
| public void setUserDao(UserDao userDao){ this.userDao = userDao; }
|
之前是主动创建对象,控制权在程序员手上。
使用set之后,是被动接受对象。
3. Hello Spring
pojo中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package com.hou.pojo;
public class Hello {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override public String toString() { return "Hello{" + "name='" + name + '\'' + '}'; } }
|
resource种
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="com.hou.pojo.Hello"> <property name="name" value="Spring"/> </bean> </beans>
|
test
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import com.hou.pojo.Hello; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Hello hello = (Hello) context.getBean("hello"); System.out.println(hello.toString()); } }
|
bean = 对象
id = 变量名
class = new的对象
property 相当于给对象中的属性设值
核心用set注入
第一个文件中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userdaomysql" class="com.hou.dao.UserDaoMysqlImpl"></bean>
<bean id="userServiceImpl" class="com.hou.service.UserServiceImp"> <property name="userDao" ref="userdaomysql"/> </bean>
</beans>
|
4. IOC创建对象的方式
- 使用无参构造创建对象,默认。
- 使用有参构造
下标赋值
1 2 3 4 5 6 7 8 9 10
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.hou.pojo.User"> <constructor-arg index="0" value="hou"/> </bean> </beans>
|
类型赋值(不建议使用)
1 2 3
| <bean id="user" class="com.hou.pojo.User"> <constructor-arg type="java.lang.String" value="dong"/> </bean>
|
直接通过参数名
1 2 3
| <bean id="user" class="com.hou.pojo.User"> <constructor-arg name="name" value="hou"></constructor-arg> </bean>
|
Spring类似于婚介网站!
你想不想要,对象都在里面。注册bean之后用不用被实例化。
5. Spring配置
别名
1 2 3 4 5
| <bean id="user" class="com.hou.pojo.User"> <constructor-arg name="name" value="hou"></constructor-arg> </bean>
<alias name="user" alias="user2aaa"/>
|
Bean的配置
- id:bean的id标识符
- class:bean对象所对应的类型
- name:别名,更高级,可以同时取多个别名。
import
一般用于团队开发,它可以将多个配置文件,导入合并为一个
1
| <import resource="beans.xml"/>
|
6. DI依赖注入
构造器注入
set方式注入(重点)
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
- 复杂类型
- 真实测试对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| package com.pojo;
import java.util.*;
public class Student {
private String name; private Address address;
private String[] books; private List<String> hobbies;
private Map<String, String> card; private Set<String> game;
private Properties infor; private String wife;
@Override public String toString() { return "Student{" + "name='" + name + '\'' + ", address=" + address + ", books=" + Arrays.toString(books) + ", hobbies=" + hobbies + ", card=" + card + ", game=" + game + ", infor=" + infor + ", wife='" + wife + '\'' + '}'; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class Address { private String address;
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
@Override public String toString() { return "Address{" + "address='" + address + '\'' + '}'; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.pojo.Address"> <property name="address" value="xian"></property> </bean>
<bean id="student" class="com.pojo.Student"> <property name="name" value="hou"/> <property name="address" ref="address"/>
<property name="books"> <array> <value>三国</value> <value>西游</value> <value>水浒</value> </array> </property>
<property name="hobbies"> <list> <value>eat</value> <value>drink</value> <value>play</value> </list> </property>
<property name="card"> <map> <entry key="1" value="12"/> <entry key="2" value="23"/> </map> </property>
<property name="game"> <set> <value>wangzhe</value> <value>daota</value> <value>lol</value> </set> </property>
<property name="wife"> <null></null> </property>
<property name="infor"> <props> <prop key="id">20200405</prop> <prop key="name">hdk</prop> </props> </property> </bean>
</beans>
|
第三方
p标签和c标签
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package com.pojo;
public class User {
private String name; private int age;
public User() { }
public User(String name, int age) { this.name = name; this.age = age; }
@Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?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:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="use" class="com.pojo.User" p:name="dong" p:age="10"> </bean>
<bean id="use2" class="com.pojo.User" c:name="kun" c:age="19"></bean> </beans>
|
bean的作用域

- 单例模式(默认)
1
| <bean id="use2" class="com.pojo.User" c:name="kun" c:age="19" scope="singleton"></bean>
|
- 原型模式: 每次从容器中get的时候,都产生一个新对象!
1
| <bean id="use2" class="com.pojo.User" c:name="kun" c:age="19" scope="prototype"></bean>
|
- 其余的request、session、application这些只能在web开放中使用!
7. Bean的自动装配
- 自动装配是Spring是满足bean依赖的一种方式
- Spring会在上下文自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
- 在xml中显示配置
- 在java中显示配置
- 隐式的自动装配bean 【重要】
环境搭建:一个人有两个宠物
Byname自动装配:byname会自动查找,和自己对象set对应的值对应的id
保证所有id唯一,并且和set注入的值一致
Bytype自动装配:byType会自动查找,和自己对象属性相同的bean
保证所有的class唯一
1 2 3 4 5
| public class Cat { public void jiao(){ System.out.println("miao"); } }
|
1 2 3 4 5 6 7
| public class Dog {
public void jiao(){ System.out.println("wow"); }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package com.pojo;
public class People {
private Cat cat; private Dog dog; private String name;
@Override public String toString() { return "People{" + "cat=" + cat + ", dog=" + dog + ", name='" + name + '\'' + '}'; }
public Cat getCat() { return cat; }
public void setCat(Cat cat) { this.cat = cat; }
public Dog getDog() { return dog; }
public void setDog(Dog dog) { this.dog = dog; }
public String getName() { return name; }
public void setName(String name) { this.name = name; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat11" class="com.pojo.Cat"/> <bean id="dog" class="com.pojo.Dog"/> <bean id="people" class="com.pojo.People" autowire="byType"> <property name="name" value="hou"></property> </bean>
</beans>
|
使用注解自动装配
jdk1.5支持的注解,spring2.5支持的注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
导入context约束
1 2 3 4 5 6 7 8 9 10 11 12
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
|
@Autowire
在属性上个使用,也可以在set上使用
我们可以不用编写set方法了
1 2 3 4 5 6 7
| public class People { @Autowired private Cat cat; @Autowired private Dog dog; private String name; }
|
1
| @Nullable 字段标志的注解,说明这个字段可以为null
|
如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候
我们可以使用@Qualifier(value = “dog”)去配合使用,指定一个唯一的id对象
1 2 3 4 5 6 7 8
| public class People { @Autowired private Cat cat; @Autowired @Qualifier(value = "dog") private Dog dog; private String name; }
|
@Resource(name=”dog”)也可以
区别:
8. 使用注解开发
在spring4之后,必须要保证aop的包导入
使用注解需要导入contex的约束
1 2 3 4 5 6 7 8 9 10 11 12
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
|
- 属性如何注入
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @Component public class User { @Value("dong") private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; } }
|
- 衍生的注解
@Component有几个衍生注解,会按照web开发中,mvc架构中分层。
- dao (@Repository)
- service(@Service)
- controller(@Controller)
这四个注解功能一样的,都是代表将某个类注册到容器中
- 作用域
@Scope(“singleton”)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Component @Scope("prototype") public class User {
@Value("dong") private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; } }
|
小结:
xml与注解
- xml更加万能,维护简单
- 注解,不是自己的类,使用不了,维护复杂
最佳实践:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/> <context:component-scan base-package="com.pojo"/>
</beans>
|
9. 使用java方式配置spring
JavaConfig
Spring的一个子项目,在spring4之后,,他成为了核心功能
1 2 3 4 5 6 7 8 9 10 11
| @Configuration @ComponentScan("com.pojo") @Import(Config2.class) public class MyConfig {
@Bean public User getUser(){ return new User(); }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| @Component public class User {
@Value("dong") private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
|
这种纯java配置方式
在springboot中,随处可见
10. 动态代理
动态代理和静态代理
角色一样
动态代理类是动态生成的,不是我们直接写好的!
动态代理:基于接口,基于类
- 基于接口:JDK的动态代理【使用】
- 基于类:cglib
- java字节码
InvocationHandler
Proxy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy;
public class ProxyInvocation implements InvocationHandler {
private Rent rent;
public void setRent(Rent rent) { this.rent = rent; }
public Object getProxy(){ return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this); }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { seeHouse(); Object result = method.invoke(rent, args); fare(); return result; }
public void seeHouse(){ System.out.println("see house"); }
public void fare(){ System.out.println("fare"); } }
|
1 2 3
| public interface Rent { void rent(); }
|
1 2 3 4 5
| public class Host implements Rent { public void rent() { System.out.println("host rent"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class Client {
public static void main(String[] args) { Host host = new Host();
ProxyInvocation proxyInvocation = new ProxyInvocation();
proxyInvocation.setRent(host);
Rent proxy = (Rent) proxyInvocation.getProxy();
proxy.rent(); } }
|
11.AOP
1 2 3 4 5 6 7
| <dependencies> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> </dependencies>
|
方法一:使用spring接口【springAPI接口实现】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| <?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beanss https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userservice" class="com.service.UserServiceImp"></bean> <bean id="log" class="com.log.Log"/> <bean id="afterlog" class="com.log.AfterLog"/>
<aop:config> <aop:pointcut id="point" expression="execution(* com.service.UserServiceImp.*(..))"/> <aop:advisor advice-ref="log" pointcut-ref="point"/> <aop:advisor advice-ref="afterlog" pointcut-ref="point"/> </aop:config>
</beans>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class UserServiceImp implements UserService {
public void add() { System.out.println("add"); }
public void delete() { System.out.println("delete"); }
public void query() { System.out.println("query"); }
public void update() { System.out.println("update"); } }
|
1 2 3 4 5 6 7 8 9 10 11 12
| import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice { public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println(target.getClass().getName()+method.getName()); } }
|
1 2 3 4 5 6 7
| public class AfterLog implements AfterReturningAdvice {
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable { System.out.println(method.getName()+returnValue); } }
|
1 2 3 4 5 6 7 8
| public class Mytest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("ApplcationContext.xml"); UserService userService = (UserService) context.getBean("userservice"); userService.add(); } }
|
方法二:自定义来实现AOP【主要是切面定义】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| <?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userservice" class="com.service.UserServiceImp"></bean> <bean id="log" class="com.log.Log"/> <bean id="afterlog" class="com.log.AfterLog"/>
<bean id="diy" class="com.diy.DiyPointcut"> </bean> <aop:config> <aop:aspect ref="diy"> <aop:pointcut id="point" expression="execution(* com.service.UserServiceImp.*(..))"/> <aop:before method="before" pointcut-ref="point"/> <aop:after method="after" pointcut-ref="point"/> </aop:aspect> </aop:config>
</beans>
|
1 2 3 4 5 6 7 8 9 10
| public class DiyPointcut {
public void before(){ System.out.println("before"); }
public void after(){ System.out.println("after"); } }
|
方法三:注解方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="ann" class="com.diy.Annotation"></bean> <aop:aspectj-autoproxy/> <bean id="userservice" class="com.service.UserServiceImp"></bean> </beans>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before;
@Aspect public class Annotation {
@Before("execution(* com.service.UserServiceImp.*(..))") public void before(){ System.out.println("before"); }
@After("execution(* com.service.UserServiceImp.*(..))") public void after(){ System.out.println("after"); }
@Around("execution(* com.service.UserServiceImp.*(..))") public void around(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("around");
Object proceed = joinPoint.proceed();
System.out.println("after around"); } }
|
12. 整合mybatis
文档: https://mybatis.org/spring/zh/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| <?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"> <parent> <artifactId>spring-study</artifactId> <groupId>com.hou</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion>
<artifactId>spring-10-mybatis</artifactId>
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.4</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.3.RELEASE</version> </dependency>
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies>
<build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
</project>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <?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>
<typeAliases> <package name="com.pojo"/> </typeAliases>
<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://111.230.212.103:3306/mybatis?userSSL=true& userUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="hdk123"/> </dataSource> </environment> </environments>
<mappers> <mapper class="com.mapper.UserMapper"/> </mappers> </configuration>
|
1 2 3 4 5 6 7 8 9 10 11 12
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.UserMapper">
<select id="selectUser" resultType="user"> select * from mybatis.user; </select>
</mapper>
|
1 2 3
| public interface UserMapper { List<User> selectUser(); }
|
整合
方法一:

UserMapperImpl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package com.mapper;
import com.pojo.User; import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; }
public List<User> selectUser() { UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class); return mapper.selectUser(); } }
|
mybatis.xml
1 2 3 4 5 6 7 8 9 10 11 12
| <?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>
<typeAliases> <package name="com.pojo"/> </typeAliases>
</configuration>
|
spring.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| <?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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true& userUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="hdk123"/> </bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource" /> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/mapper/UserMapper.xml"/> </bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
<bean id="userMapper" class="com.mapper.UserMapperImpl"> <property name="sqlSessionTemplate" ref="sqlSession"></property> </bean>
</beans>
|
test
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import com.mapper.UserMapper; import com.pojo.User; import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
public class Mytest {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) { System.out.println(user); } } }
|
方法二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true& userUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="hdk123"/> </bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource" /> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/mapper/UserMapper.xml"/> </bean>
<bean id="userMapper2" class="com.mapper.UserMapperIml2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean>
</beans>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| package com.mapper;
import com.pojo.User; import org.apache.ibatis.session.SqlSession; import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperIml2 extends SqlSessionDaoSupport implements UserMapper { public List<User> selectUser() { SqlSession sqlSession = getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser(); } }
|
13. 声明式事务
- 要么都成功,要么都失败
- 十分重要,涉及到数据一致性
- 确保完整性和一致性
事务的acid原则:
原子性
一致性
隔离性
持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会被影响。
Spring中的事务管理
声明式事务
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| <?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-tx.aop">
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://111.230.212.103:3306/mybatis?userSSL=true& userUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="hdk123"/> </bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="datasource" /> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/mapper/*.xml"/> </bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <constructor-arg ref="datasource" /> </bean>
<tx:advice id="tx1" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add" propagation="REQUIRED"/> <tx:method name="delete" propagation="REQUIRED"/> <tx:method name="update" propagation="REQUIRED"/> <tx:method name="*" propagation="REQUIRED"/> <tx:method name="query" read-only="true"/> </tx:attributes> </tx:advice>
<aop:config> <aop:pointcut id="txpointxut" expression="execution(* com.mapper.*.*(..))"/> <aop:advisor advice-ref="tx1" pointcut-ref="txpointxut"/> </aop:config>
</beans>
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?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 https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper2" class="com.mapper.UserMapperIml2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean>
</beans>
|
Mapper
1 2 3 4 5 6 7 8 9 10 11
| package com.mapper;
import com.pojo.User;
import java.util.List;
public interface UserMapper { List<User> selectUser(); int addUser(User user); int delete(int id); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.UserMapper"> <select id="selectUser" resultType="user"> select * from mybatis.user; </select>
<insert id="addUser" parameterType="user"> insert into mybatis.user (id, name, pwd) values (#{id}, #{name}, #{pwd}) </insert>
<delete id="delete" parameterType="int"> delete from mybatis.user where id=#{id} </delete> </mapper>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package com.mapper;
import com.pojo.User; import org.apache.ibatis.session.SqlSession; import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperIml2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() { User user = new User(6, "long", "zhi"); SqlSession sqlSession = getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); mapper.addUser(user); mapper.delete(6); return mapper.selectUser(); }
public int addUser(User user) { return getSqlSession().getMapper(UserMapper.class).addUser(user); }
public int delete(int id) { return getSqlSession().getMapper(UserMapper.class).delete(id); } }
|