1、Spring
1.1、Spring 简介
-
Spring框架以interface21框架为基础,2004年3月24日发布正式版。
-
原理:整合了现有的技术框架。
-
SSH : Struct2 + Spring + hibernate
-
SSM : SpringMvc + Spring + Mybatis
-
导包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.8.RELEASE</version> </dependency>
1.2、优点
- Spring是一个开源的免费的框架(容器)
- Spring是一个轻量级的、非入侵式的框架
- 控制反转(IOC),面向切面编程呢个(AOP)
- 支持事务的处理,对框架整合的支持
1.3、 组成

1.4、拓展
-
Spring Boot
- 一个开发的脚手架
- 基于SpringBoot可以快速的开发单个微服务
- 约定大于配置
-
Spring Cloud
- SpringCloud是基于SpringBoot实现的
承上启下的作用
2、IOC理论推导
1.UserDao
2.UserDaoimpl实现类
3.UserService
4.UserServiceimpl业务实现类
在业务实现中,可能需要根据用户需求去修改源代码!如果程序代码量较大,修改成本高。
使用Set接口实现。
private userDao userDao;
public void set(userDao useDao) {
this.userDao = useDao;
}
- 之前,程序主动创建对象,控制权在程序员手上。
- 使用了Set注入后,程序不再具有主动性,变成了被动的接受对象。
2.1、IOC本质
**控制反转IOC(inversion of Control),是一种思想,DI(依赖注入)是实现IOC的方法。**面向对象过程中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,即获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到零配置的目的。
3、helloSpring
//获取Spring的上下文对象
ApplicationContext context =new ClassPathXmlApplicationContext("Bean.xml");
Hello hello =(Hello) context.getBean("hello");
System.out.println(hello.getStr());
4、IOC创建对象的方式
1.使用无参构造创建对象,默认
2.假设我们要使用有参构造创建对象
1.参数为Bean对象
//1.方法体
public class ThingOne {
//有参构造,参数为对象
public ThingOne(ThingTwo thingTwo, ThingThree thingThree) {
// ...
}
}
//2.Bean.xml
<beans>
<bean id="beanOne" class="ThingOne">
<constructor-arg ref="beanTwo"/>
<constructor-arg ref="beanThree"/>
</bean>
<bean id="beanTwo" class="ThingTwo"/>
<bean id="beanThree" class="ThingThree"/>
</beans>
2.参数为简单类型,类型匹配,<不常用>
//1.方法体
public class ExampleBean {
private int years;
private String ultimateAnswer;
//有参构造
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
//2.Bean.xml
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>
3.参数索引
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean
4.参数名称<常用>
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg name="years" value="7500000"/>
<constructor-arg name="ultimateAnswer" value="42"/>
</bean>
5.注解@ConstructorProperties显示命名构造函数参数
public class ExampleBean {
@ConstructorProperties({"years", "ultimateAnswer"})
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
总结:在配置加载文件的时候,容器中管理的对象就已经初始化了
5、Spring的配置
5.1 、别名
<alias name="userServiceimpl" alias="serviceimpl"/>
5.2、Bean的配置
<!--
id: bean的唯一标识符,也就相当相当于对象名
class: bean对象对应的全权限名:包名 + 类型
name: 也是别名,而且name可以同时取多个别名
-->
<bean id="userServiceimpl" class="com.jeffshaw.Service.userServiceimpl">
<property name="userDao" ref="userDaoSqlimpl"/>
</bean>
5.3、import
import用于团队开发,将多个配置文件,导入合并成一个。
//可置于applicationContext.xml中
<import resource="bean1.xml">
<import resource="bean2.xml">
<import resource="bean3.xml">
6、依赖注入
6.1、构造器注入
-
pojo对象
public class User { private String name; public User(String name){ this.name = name; } public void userShow(){ System.out.println(this.name); } }
-
beans.xml
<!--使用构造器注入,有参--> <bean id="user" class="com.jeffshaw.pojo.User"> <constructor-arg name="name" value="张三"/> </bean>
6.2、Setter注入<重点>
- 依赖注入:set注入!
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中所有的属性,由容器来注入
【环境搭建】
1.复杂类型
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
2.真实测试类型
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbys;
private Map<String,String> cards;
private Set<String> games;
private String Grilfriend;
private Properties info;
getter() + Setter()
}
3.beans.xml
<!--使用Setter依赖注入-->
<bean id="adsress" class="com.jeffshaw.pojo.Address"/>
<bean id="student" class="com.jeffshaw.pojo.Student">
<!--第一种普通注入-->
<property name="name" value="张三"/>
<!--第二种普通注入,Bean注入,ref-->
<property name="address" ref="adsress"/>
<!--第三种,数组注入-->
<property name="books">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>三国演义</value>
<value>水浒传</value>
</array>
</property>
<!--第四种List注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>跳舞</value>
<value>运动</value>
</list>
</property>
<!--第五种Map注入-->
<property name="cards">
<map>
<entry key="身份证" value="151515"/>
<entry key="银行卡" value="145151"/>
</map>
</property>
<!--第六种Set注入-->
<property name="games">
<set>
<value>LOL</value>
<value>Dota</value>
</set>
</property>
<!--第六种空注入-->
<property name="grilfriend">
<null/>
</property>
<!--第七种property注入-->
<property name="info">
<props>
<prop key="学号">11111</prop>
<prop key="性别">男</prop>
</props>
</property>
</bean>
4.测试类
public void SetterDITest(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student =(Student) context.getBean("student");
System.out.println(student.getName());
}
6.3、拓展方式命名
我们可以通过p命名空间和c命名空间
1.bean.xml
<bean id="blog" class="com.jeffshaw.pojo.Blog" p:age="21p" p:name="blogp"/>
<bean id="blog2" class="com.jeffshaw.pojo.Blog" c:age="18c" c:name="blogC"/>
注意:p命名和c命名不能直接使用,需要导入xml约束,如下:
xmlns:p="http://www.springframework.org/schema/p
xmlns:c="http://www.springframework.org/schema/c
2.Test,测试类
public void PAndCTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Blog blog = context.getBean("blog", Blog.class);
Blog blog2 = context.getBean("blog2", Blog.class);
System.out.println(blog);
System.out.println(blog2);
}
6.4、bean的作用域
1.单例模式(Spring的默认机制)
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>
2.原型模式:每次从容器种get的时候,都会产生一个新对象!
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
3.其余的request、session、application只能在web开发中使用到。
7、Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式!
- Spring会在上下文中自动寻找,并自动给bean装配属性!
在Spring中三种装配的方式
1.在xml中显示的配置
2.在java中显示配置
3.隐式的自动装配bean【重要】
7.1、ByName自动装配
<!--byName:会自动在容器上下文查找,和自己对象set方法后面的值对应的beanid! setName()-->
<bean id="man" class="com.something.Man" autowire="byName"/>
7.2、ByType自动装配
<!--byType:会自动在容器上下文查找,和自己对象属性类型相同的bean
<bean id="man" class="com.something.Man" autowire="byType"/>
小结:
-
byName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
-
byType,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
7.3、使用注解自动装配
1.导入约束:contex约束
2.配置注解的支持:
<beans
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
>
<context:annotation-config/>
</beans>
-
@Autowired
直接在属性上用即可!也可以在set方法上使用!
使用Autowired可以不用再写set方法,前提是这个自动装配的属性再IOC(Spring)容器中存在
public class Man {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
...
}
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,可以使用@Qualifier(valuer="id")
-
@Resource注解
存在多个bean时需注解name值
<bean id="cat1" class="com.jeffshaw.pojo.Cat" /> <bean id="dog1" class="com.jeffshaw.pojo.Dog" /> <bean id="cat2" class="com.jeffshaw.pojo.Cat" /> <bean id="dog2" class="com.jeffshaw.pojo.Dog" /> <bean id="dog2" class="com.jeffshaw.pojo.Dog" /> </bean> public class Man { @Resource(name = "cat1") private Cat cat; @Resource(name ="dog2") private Dog dog; private String name; ... }小结:@Resource和@Autowired的区别:
小结:@Autowired和@Resource的去呗:
- 都是用来自动装配的,都可以放在属性字段上
- 都可以通过byName/byTyep实现,且对象存在
- @Autowired优先byType,再byName,配合Qualifier使用
- @Resource默认通过byName实现,如果找不到,再通过byType实现。
8、使用注解开发
在Spring4之后,要使用注解开发,需要保证aop的包导入了
使用注解需要导入context约束,增加注解支持!
<?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"
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
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
">
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.jeffshaw.pojo"/>
<context:annotation-config/>
</beans>
1.bean
2.属性如何注入
<!--------实体类------>
/*@Component 组件,等价于<bean id="user" class="....User"/>
* */
@Component
public class User {
//@value("***")
public String name = "jeffshaw";
}
3.衍生的注解
@Component有几个注解衍生,在web开发中,会按照mvc三层架构分层!
- dao【@Repository】
- service 【@Service】
- controller 【@Controller】
这四个注解功能是一样的,都是代表将某个类注册到Spring中,装配Bean。
4.作用域
@scope("singleton")
@Component
public class User {
//@value("***")
public String name = "jeffshaw";
}
小结:
xml与注解:
- xml更加万能,适用于任何场合,维护简单方便
- 注解不是自己类使用不了,维护相对复杂
xml与注解最佳实践
-
xml用来管理bean;
-
注解只负责完成属性的注入;
-
使用过程中,必须让注解生效,就需要开启注解的支持.
<context:component-scan base-package="com.jeffshaw"/> <context:annotation-config/>
9、使用Java的方式配置Spring
现在Spring的新Java配置支持中的主要工件是-带 @Configuration
注释的类和-带@Bean
注释的方法。
1.@Configuration+@bean使用
@Configuration
public class ServiceConfig {
@Bean
public User user( ) {
return new User();
}
}
2.@@Configuration+@ComponentScan使用
@Configuration
@ComponentScan("com.jeffshaw")
public class appConfig {}
重点:@ComponentScan将指定包下的被@Repository、@Service、@Controller、@RestController、@Component、@Configuration注解下的Bean自动扫描注入到Spring IOC容器中,由Spring IOC容器统一管理这些Bean。
3.测试
public void Test1(){
//需要通过AnnotationConfig来获取容器
ApplicationContext context = new AnnotationConfigApplicationContext(appConfig.class);
User bean = context.getBean(User.class);
System.out.println(bean);
}
10、代理模式
为什么要学习代理模式?因为这是SpringAOP的底层!【SpringAOP和SpringMVC】
- 代理模式:为一个对象提供一个替身,以控制对这个对象的访问
- 优点:可以在目标对象的实现的基础上,增强额外的功能操作,即扩展目标对象的功能。
- 缺点:代理需要与目标对象实现相同的接口,在接口维护时,需要同时修改。
- 代理模式:静态代理、动态代理(JDK代理、接口代理)和Cglib代理(可以在内存动态的创建对象,二不需要实现接口,属于动态代理的范畴)
10.1、静态代理
//代理
public class houseProxy {
private Hire hire;
public houseProxy(Hire hire) {
this.hire = hire;
}
public void rent(){
hire.rent();
}
//测试
public void test1(){
Hire hire = new Landlord();
houseProxy houseProxy = new houseProxy(hire);
/* houseProxy.setHire(hire);*/
houseProxy.rent();
}
10.2、动态代理
- 动态代理和静态代理角色一样
- 动态代理类是动态生成的,不是直接写好的
- 动态代理分为两大类:基于接口的动态代理,基于类的动态代理
- 基于接口---JDK动态代理
- 基于类:cglib
- java字节码实行
需要了解两个类:Proxy:代理 , invocationHandler :调用处理程序
-
代理类包:Java.lang.reflect.Proxy
-
JDK实现代理只需要使用new ProxyInstance方法,但是该方法需要接受三个参数,完整的写法:
static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,invocationHandler h)
- ClassLoader loader:指当前目标对象使用的类加载器,互殴去加载器的方法固定
- Class<?>[] interfaces:目标对象实现的接口类型,使用泛型方法确认类型
- invocationHandler h:事件处理,执行目标对象的方法时,会触发事件处理器的方法,会把当前执行的目标对象方法作为参数
(1)根据参数loader和interfaces调用方法 getProxyClass(loader, interfaces)创建代理类$Proxy0.$Proxy0类 实现了interfaces的接口,并继承了Proxy类.
(2)实例化$Proxy0并在构造方法中把DynamicSubject传过去,接着$Proxy0调用父类Proxy的构造器,为h
动态代理类
public class ProxyFactory {
private Object target;
public ProxyFactory(Object target) {
this.target = target;
}
public void see(){
System.out.println("监考");
}
public Object getProxy(){
System.out.println();
/*InvocationHandler handler = new MyInvocationHandler(...);
Class<?> proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(), Foo.class);
Foo f = (Foo) proxyClass.getConstructor(InvocationHandler.class).
newInstance(handler);
*/
//获取目标对象的类加载器及目标对象的接口类型,类加载器统一为ApplicationClassLoader
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
see();
Object ReturnVal = method.invoke(target, args);
return ReturnVal;
}
});
}
}
测试类
public void Test3(){
ITeacher teacher = new Teacher();
ITeacher proxy = (ITeacher)new ProxyFactory(teacher).getProxy();
/*
ProxyFactory proxyFactory = new ProxyFactory(teacher);
ITeacher proxy = (ITeacher)proxyFactory.getProxy();
*/
}
11、AOP
11.1、概念
AOP Aspect Oriented Programming(面向切面编程) ,通过预编译方式呵运行期动态代理实现程序功能的统一维护的一种技术。
作用:在程序运行期间,不修改源码对已有方法进行增强。
实现方式,使用动态代理方式
Joinpoint(连接点):是指被拦截到的点,在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。
Pointcut(切入点):是指我们要对那些Joinpoint进行拦截的定义。
advice(通知/增强):
所谓通知是指拦截到Joinpoint之后索要做得事情就是通知。
通知的类型:前置通知、后置通知、异常通知、最终通知,环绕通知。
Target(目标对象):代理的目标对象
Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。
spring采用动态代理植入,而AspectJ采用编译期织入和类装载期织入。
proxy(代理):一个类被AOP织入增强后,产生一个结果代理类
Aspect(切面)是切入点和通知(引介)的结合。
11.2、使用Spring实现AOP
[重点]使用AOP织入,需要导入一个依赖包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
**方式一:**使用Spring的API接口
继承接口:
public class Log implements MethodBeforeAdvice {}
public class AfterLog implements AfterReturningAdvice
xml配置:
<!--配置AOP,需要导入AOP的约束-->
<aop:config>
<!--切入点: expression:表达式,execution(要执行的位置!* * * *),(..)指任意参数-->
<aop:pointcut id="pointcut" expression="execution(* com.jeffshaw.Service.UserServiceImpl.*(..) )"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
测试类:
@org.junit.Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = (UserService)context.getBean("userService");
service.add();
}
方式二:使用自定义类来实现
自定义类:
public class DivPointCut {
public void before(){
System.out.println("执行前的方法");
}
public void after(){
System.out.println("执行后的方法");
}
}
xml配置:
<aop:config>
<!--自定义切面,ref引用的类-->
<aop:aspect ref="divPointCut">
<aop:pointcut id="point" expression="execution(* com.jeffshaw.Service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
方式三:使用注解实现
xml配置:
<!--开启注解扫描-->
<context:component-scan base-package="com.jeffshaw"/>
<!--开启Asperct生成代理对象-->
<aop:aspectj-autoproxy/>
代理类:
@Component
@Aspect//标注这是一个切面
public class annotecationpoint {
@Before("execution(* com.jeffshaw.Service.UserServiceImpl.*(..))")
public void before(){
System.out.println("自定义注解执行前方法");
}
@After("execution(* com.jeffshaw.Service.UserServiceImpl.*(..))")
public void after(){
System.out.println("自定义注解执行后方法");
}
}
实体类:
@Component
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("添加用户");
}
public void delete() {
System.out.println("删除用户");
}
public void update() {
System.out.println("更新用户");
}
public void query() {
System.out.println("查询用户");
}
}
12、整合Mybatis
步骤:
-
导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关
- aop织入
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> </dependencies>
-
编写配置文件
-
测试
12.1、回忆Mybatis
- 编写实体类
- 编写核心配置类(mybatis-config.xml)
- 编写接口
- 编写Mapper.xml
- 测试
注意:
- mybatis-config.xml中需要绑定resource(././.xml)
- UserMapper.xml中需要命名空间:namespace;
mybatis-config.xml:
<configuration>
//配置数据库连接
<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://localhost:3306/eesy_mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="a123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/jeffshaw/Dao/UserMapper.xml"/>
</mappers>
</configuration>
userMpaaer.xml:
<mapper namespace="com.jeffshaw.Dao.UserMapper">
<select id="findById" parameterType="int" resultType="user">
select * from user where id = #{id}
</select>
</mapper>
测试类:
public void test1() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = sessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> users = mapper.selectUser();
for (User user : users) {
System.out.println(user);
}
}
12.2、Mybatis-spring的整合(方式一)
如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
步骤如下:
- Springxml中配置DataSource(使用Spring的数据源替换Mybatis的配置)
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis?useSSl=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="a123456"/>
</bean>
-
配置SqlSessionFactory
<!--引入SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!--绑定Mybatis配置文件--> <property name="configLocation" value="classpath:Mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/jeffshaw/Mapper/UserMapper.xml"/> </bean>
-
配置sqlSession
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--没有set方法,只能使用构造方法注入--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
-
配置userMapper实现类
目的是将sqlSession注入到实现类中,使Session操作封装到实体类中
<bean id="userMapper" class="com.jeffshaw.Mapper.UserMapperImpl"> <constructor-arg ref="sqlSession"/> </bean>
public class UserMapperImpl implements UserMapper { //所有操作都用sqlSession来执行,现在使用SqlSessionTemplate private SqlSessionTemplate sqlSessionTemplate; public UserMapperImpl(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } public List<User> selectUser() { /* UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class); return mapper.selectUser();*/ return sqlSessionTemplate.getMapper(UserMapper.class).selectUser(); } }
-
测试类
public void test2() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
UserMapper mapper = context.getBean(UserMapper.class);
List<User> users = mapper.selectUser();
for (User user : users) {
System.out.println(user);
}
}
12.3、Mybatis-spring的整合(方式二)
-
Springxml中配置DataSource(使用Spring的数据源替换Mybatis的配置)<同上>
-
配置SqlSessionFactory <同上>
-
配置userMapper实现类
目的是将sqlSession注入到实现类中,使Session操作封装到实体类中
<bean id="userMapper" class="com.jeffshaw.Mapper.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper { //SqlSessionDaoSupport内置getSqlSession,不用在application.xml中注入 public List<User> selectUser() { return getSqlSession().getMapper(UserMapper.class).selectUser(); } }
13、Spring声明式事务
事务得ACID原则(要么成功,要么都失败):
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏。
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久化写存储器中
13.1、spring中的事务管理
-
声明式事务: AOP
-
编程式事务(原有代码中try...catch...)
1、配置声明式事务
- application.xml配置
<!--声明事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知的类-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.jeffshaw.Mapper.UserMapperImpl2.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
- 实体类方法
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
//SqlSessionDaoSupport内置getSqlSession,不用在application.xml中注入
public List<User> selectUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
User user = new User(14,"芯芯",new Date(),"女","赣州");
mapper.insertUser(user);
mapper.deleteUser(13);
return selectUser();
}
public void deleteUser(int id) {
getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
public void insertUser(User user) {
getSqlSession().getMapper(UserMapper.class).insertUser(user);
}
}
注意:每次session方法调用后将关闭,默认提交事务。属编程式事务。定义声明式事务后,方法必须全部通过后提交。
评论区