1、IOC
2、HelloSpring
1、实现步骤
- 导入Jar包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
- 创建实体类对象
public class Hello {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("Hello,"+ name );
}
}
- 配置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">
<!--bean就是java对象 , 由Spring创建和管理-->
<bean id="hello" class="com.kuang.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
- 测试(通过CPX加载)
@Test
public void test(){
//获取Spring的上下文对象,可以读取多个:
//ClassPathXmlApplicationContext(“beans1.xml,beans2.xml”)
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//getBean : 参数即为spring配置文件中bean的id
Hello hello = (Hello) context.getBean("hello");
//Hello hello = context.getBean("hello",Hello.class);
hello.show();
}
2、小结
IOC : 对象由Spring来创建,管理,装配!
控制:谁来控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring来创建的
反转:程序本身不创建对象,而变成被动的接收对象
依赖注入:就是利用 set方法 来进行注入的
3、IOC创建对象方式
实体类
public class User{
private String userName;
//有参构造
public User(String userName){
this.userName = userName;
}
//getter、setter
}
1、【默认】使用无参构造创建对象
如果实体类中没有无参构造方法,运行会报错
<bean id="user" class="com.huairong.User">
<property name="userName" value="怀荣"/>
</bean>
2、有参构造创建对象
1. 参数下标赋值
index ==> 有参构造中传入的第几个参数,从0开始
<bean id="user" class="com.huairong.pojo.User">
<constructor-arg index="0" value="怀荣"/>
</bean>
2.参数类型赋值
type ==> 有参构造方法传入参数的数据类型
基本类型可以写如 int
引用类型必须写 全限定名
(如果两个参数类型都是String,就会出错)
<bean id="user" class="com.huairong.pojo.User">
<constructor-arg type="java.lang.String" value="怀荣"/>
</bean>
3.直接通过参数名
- 方式一:
name ==> 有参构造方法的参数名
<bean id="user" class="com.huairong.pojo.User">
<constructor-arg name="userName" value="怀荣"/>
</bean>
- 方式二:
ref ==> 引用容器中的bean
实体类:
public class Person{
private Dog dog;
private Cat cat;
public Person(Dog dog,Cat cat){
this.dog = dog;
this.cat = cat;
}
//getter、setter
}
beans.xml文件:
<bean id="dog" class="com.huairong.Dog"/>
<bean id="cat" class="com.huairong.Cat"/>
<bean id="person" class="com.huairong.Person">
<constructor-arg ref="dog"/>
<constructor-arg ref="cat"/>
</bean>
3、总结
1、在配置文件加载的时候,容器中管理的对象就已经初始化了
2、Spring容器中一个对象只有一份实例
User user1 = context.getBean("user",User.class);
User user2 = context.getBean("user",User.class);
System.out.println(user1 == user2); //true
4、Spring配置
1、alias 别名
添加了别名,也可以通过别名获取到bean
- xml中
<alias name="user" alias="aliasName"/>
- 测试
User user1 = context.getBean("user",User.class);
User user2 = context.getBean("aliasName",User.class);
2、bean 的配置
1. 通用配置
id:bean的唯一标示符
class:bean对象所对应的全限定名(包名+类型)
name:也是取别名,而且可同时取多个别名
<bean id="user" class="com.huairong.User" name="u1 u2,u3;u4">
<property name="userName" value="怀荣"/>
</bean>
2. 作用域
3. 自动装配
3、import 导入
一般用于团队开发,可以将多个 beans.xml 导入到一个 applicationContext.xml 中
applicationContext.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">
<!-- 导入beans.xml -->
<import resource="beans1.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>
</beans>
5、DI 依赖注入
1、构造器注入
上方已经说明
2、Set方式注入【重点】
依赖注入:Set注入
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
1. 复杂类型->环境搭建
public class Student{
private String studentName;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private String wife; //null指针
private Properties info;
//有参、无参
//getter、setter
}
public class Address{
private String addressDtl;
//有参、无参
//getter、setter
}
2. 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">
<!-- -->
<bean id="address" class="com.huairong.Address">
<property name="addressDtl" value="福州市"/>
</bean>
<bean id="student" class="com.huairong.Student">
<!-- 第一种,普通值注入,value -->
<peoperty name="studentName" value="怀荣"/>
<!-- 第二种,Bean注入,ref -->
<property name="address" ref="address"/>
<!-- 第三种,数组注入,array -->
<peoperty name="books">
<array>
<value>红楼梦</value>
<value>三国演义</value>
<value>水浒传</value>
<value>西游记</value>
</array>
</peoperty>
<!-- 第四种,集合注入,list -->
<property name="hobbies">
<list>
<value>听歌</value>
<value>打球</value>
<value>看电影</value>
</list>
</property>
<!-- 第五种,Map注入,map -->
<property name="card">
<map>
<entry key="身份证" value="350xxx"/>
<entry key="银行卡" value="621226xxx"/>
</map>
</property>
<!-- 第六种,Set注入,set -->
<property name="games">
<set>
<value>LOL</value>
<value>CS</value>
</set>
</property>
<!-- 第七种,null注入,null -->
<property name="wife">
<null/>
</property>
<!-- 第八种,peoperties注入,prop -->
<property name="info">
<props>
<prop key="学号">3177201115</prop>
<prop key="班级">17计科1班</prop>
</props>
</property>
</bean>
</beans>
3. 测试类
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
student.toString();
}
3、扩展方式注入
1. P命名空间注入
P命名空间注入,可以直接注入属性的值:property
必须要有Set方法!!
(1)导入约束
<beans xmlns:p="http://www.springframework.org/schema/p"></beans>
(2)使用
<!--普通值注入-->
<bean id="address" class="com.huairong.Address" p:info="福州"/>
<!--引用注入-->
<bean id="user" class="com.huairong.User" p:name="怀荣" p:address-ref="address"/>
2. C命名空间注入
必须要有参构造器!!
(1)导入约束
<beans xmlns:c="http://www.springframework.org/schema/c"></beans>
(2)使用
<!--普通值注入-->
<bean id="address" class="com.huairong.Address" c:info="福州"/>
<!--引用注入-->
<bean id="user" class="com.huairong.User" c:name="怀荣" c:address-ref="address"/>
3. 官网文档位置
4、作用域
1、单例模式(Spring默认机制)
该对象创建的多个实例,实际上均为同一个对象(地址相等)
<bean id="user" class="com.huairong.User" scope="singleton"/>
2、原型模式
创建的每一个实例对象都是独立的(地址不相等)
<bean id="user" class="com.huairong.User" scope="prototype"/>
6、自动装配
自动装配是Spring满足bean依赖的一种方式
Spring会在上下文中自动寻找,并自动给bean装配属性
1、Spring装配方式
1、在xml中显示的配置
2、在java中显示的配置
3、隐式的自动装配bean【重要】
2、byName自动装配
文档:Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired.
会根据实体类中的属性名,在Spring容器中自动装配相同名字的bean
如果Spring容器中没有相对应名字的bean,则会报错
(1)实体类
public class Person{
private Dog dog;
private Cat cat;
private String name;
//getter、setter
}
(2)xml自动装配
<bean id="dog" class="com.huairong.Dog"/>
<bean id="cat" class="com.huairong.Cat"/>
<bean id="people" class="com.huaiorng.People" autowired="byName">
<property name="name" value="怀荣"/>
<!--剩余两个属性会根据实体类中的属性名(dog,cat)自动在容器中寻找并装配-->
</bean>
3、byType自动装配
文档:Lets a property be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use
byType
autowiring for that bean. If there are no matching beans, nothing happens (the property is not set).将在容器中寻找相同属性类型的bean,自动装配;
如果存在多个相同属性类型的bean,则会报错;
如果没有该类型的bean,那么什么都不会发生
7、注解开发
1、注解支持
在Spring4之后,使用注解开发,必须保证aop的包导入使用注解
需要导入context约束,增加注解的支持
- 约束文件:
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd"
- 自动扫描包
<context:component-scan base-package="com.huairong.pojo"/>
- 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
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.huairong.pojo"/>
<context:annotation-config/>
</beans>
2、@Component
@Component 相当于在xml中注册
需要配置自动扫描包
- 提前在xml中配置自动扫描包
<context:component-scan base-package="com.huairong.pojo"/>
- java实体类
//@Component相当于在xml中注册<bean>
//需要配置自动扫描包
@Component
public class User{
private String name;
private int age;
}
3、@Value
使用 @Value 在属性上注入值,相当于
中的 @Value 可以放在属性上,或者 set 方法上
- java实体类
@Component
public class User{
//相当于<property id=name value="怀荣"/>
@Value("怀荣")
private String name;
}
4、衍生注解
1. @Conponent衍生注解
这几个注解功能一致,都是将某个类注册到Spring容器中,装配成
- Dao层:@Repository
- Service层:@Service
- Controller层:@Controller
2. 作用域注解
@Scope(“singleton”) 相当于
@Component
@Scope("prototype")
public class User{
@Value("怀荣")
private String name;
}
5、自动装配注解实现
- 约束文件
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd"
- 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"
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/>
<bean id="dog" class="com.huairong.Dog"/>
<bean id="cat" class="com.huairong.Cat"/>
<bean id="people" class="com.huairong.People"/>
</beans>
- 使用
public class People{
@Autowired
private Cat cat;
@Autowired
private Dog dog;
//无参构造、get、set
/* 也可以在set方法上使用
@Autowired
public void setDog(Dog dog){
this.dog = dog;
}
*/
}
- 注意点:
1、自动装配注解可以在属性或set方法上使用
2、使用自动装配注解,甚至可以不用set方法,前提是该属性存在于Spring IOC容器中
3、@Autowired是先根据 type 在Spring IOC容器中查找,如果存在多个再根据 name 查找
- 属性扩展
@Autowired注解中,required属性默认为true;
如果设置为false,则说明对个对象可以为null;
与@Nullable 等同;
public class People{
@Autowired(required = false)
private Cat cat;
public setCat(@Nullable Cat cat){
this.cat = cat;
}
}
8、Java配置类
使用java配置类,完全代替xml配置
1、@Configuration
- 配置JavaConfig
@Configuration 说明这是一个配置类,等同于一个xml文件
@Bean相当于在xml中配置
<bean id="getUser" class="com.huairong.pojo.User"></bean>
@Configuration
public class MyConfig(){
@Bean
public User getUer(){
return new User();
}
}
- 测试
AnnotationConfigApplicationContext 获取 注解上下文
对比之前是 ClassPathXmlApplicationContext
@Test
public void test(){
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User user = context.getBean("getUser",User.class);
//...
}
2、@ComponentScan
@ComponentScan(“com.huairong.pojo”)
相当于xml配置文件中的<context:component-scan base-package="com.huairong.pojo"/>
3、@Import
@Import(MyConfig.class) 导入其他java配置类
相当于xml配置文件中的
9、以上总结
自动装配小结:
自动装配是将已经在Spring容器中注册的对象,自动先按照类型在容器中查找装配,如果查找出多个同类型的对象,再按照名字查找。如果均没有查找到,则该属性值为null
注解小结:
在类上使用
@Component
注解,表明将此类交给Spring容器托管,小写的类名即为的id名; 在类上使用
@Configuration
注解,说明这是一个配置类,作用等同于xml配置文件,且同样将此类交给Spring容器托管;在此类的方法上使用 @Bean注解,等同于xml文件中注册,将返回的对象交给Spring容器托管,方法名即为 的id名;
实体类上不使用@Component注解:(即 使用注解将实体类注册到Spring容器)
(1)传统
xml配置文件
:xml文件中注册。 (2)使用
java配置类
:类上使用@Configuration注解,表明这是一个配置类。在返回该实体类对象或接口实现类的方法上使用@Bean注解,效果等同于在xml文件中注册,方法名即为该 的id名。 实体类上使用@Component注解:(即 不使用注解将实体类注册到Spring容器)
(1)传统
xml配置文件
:无需注册,只需添加自动扫描包与注解支持相关配置。 (2)使用
java配置类
:使用 @Configuration 注解,方法则无需写带有 @Bean 注解的返回该实体类对象的方法。因为@Component已经将其在Spring容器中注册过一次,如果写了的话,将等于在Spring中注册两次相同类的; (3)如果及使用了@Componet注解,又在Java配置类中使用@Bean的方法将同一个类注册了两次,且Java类中的方法名是小写的实体类名,虽然看起来像是注册了两次,但经测试发现,实际上只有
一次
实例化该对象。
10、AOP
1、使用Spring实现AOP
- 导入依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
- Servece与其实现类
public class UserService{
void add();
}
public class UserServiceImpl implement UserService{
@Override
public void add(){
System.out.println("add");
}
}
- 前置增强
public class Log implements MethodBeforeAdvice {
/*
method:目标对象的方法
objects:参数
target : 目标对象
*/
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"类,执行了"+method.getName()+"方法");
method.invoke(objects);
}
}
- 使用xml注册bean
约束文件:
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.huairong.proxy.UserServiceImpl"/>
<bean id="log" class="com.huairong.proxy.Log"/>
<!--方式一:使用原生Spring API接口-->
<!--配置aop:需要导入aop约束-->
<aop:config>
<!-- 切入点:execution表达式-->
<aop:pointcut id="pointcut" expression="execution(* com.huairong.proxy.UserServiceImpl.*(..))"/>
<!-- 执行环绕增强-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
</aop:config>
</beans>
- 测试
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//代理的是接口
UserService userService = context.getBean("userService", UserService.class);
userService.add();
//输出结果:com.huairong.proxy.UserServiceImpl类,执行了add方法
}
}
2、自定义切面实现
- 自定义切面
public class MyPointCut {
public void before(){
System.out.println("方法执行前");
}
public void after(){
System.out.println("方法执行后");
}
}
- xml配置
<!--注册bean-->
<bean id="userService" class="com.huairong.proxy.UserServiceImpl"/>
<bean id="diy" class="com.huairong.proxy.MyPointCut"/>
<!--方式二:自定义切面-->
<aop:config>
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.huairong.proxy.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
- 测试类同上
3、使用注解实现
- 切面
/**
* @Aspect 说明这是一个切面
* 代替了在xml中配置
* <aop:config>
* </aop:config>...
*/
@Aspect
@Component
public class AnnotationAspect {
/**
* Description:@Before 在方法执行前执行;参数为pointcut切入点
* @Param: []
* @Return: void
*/
@Before("execution(* com.huairong.proxy.UserServiceImpl.*(..))")
public void Before(){
System.out.println("方法执行前");
}
}
- Java配置类
//开启注解支持:(Java配置类与xml配置文件的操作对比)
//@EnableAspectJAutoProxy <==> <aop:aspectj-autoproxy>
//需使用自动扫描包注解,不然会报错
@Configuration
@ComponentScan("com.huairong.proxy")
@EnableAspectJAutoProxy
public class AnnoConfiguration {
}
- 测试类
public static void main(String[] args) {
//注意:如果是通过Java配置类获取Spring容器中的对象,则要使用AnnotationConfigApplicationContext
// Spring容器中注册是UserServiceImpl实现类,但getBean返回的不许是UserService接口!
AnnotationConfigApplicationContext conttext = new AnnotationConfigApplicationContext(AnnoConfiguration.class);
UserService userService = conttext.getBean("userServiceImpl", UserService.class);
userService.add();
}
11、整合Mybatis
1、Mybatis步骤
- 编写实体类
- 编写核心配置文件
- 编写接口
- 编写Mapper.xml
- 测试(如果xml不在resource文件中,需要注意配置静态资过滤)
2、Mybatis-Spring
- 导入依赖:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
1. 整合方式一
概括步骤:
1、将原来需要配置的
DataSource
、SqlSessionFactory
、SqlSession
注册到Spring容器中 2、编写接口实现类,并注册到Spring容器中,赋值SqlSessionTemplate
3、使用实现类测试
注意点:
1、如果Spring配置文件绑定了UserMapper.xml,那么mybatis-config中就不要重复绑定
2、被注册到Spring容器中的类必须要有无参构造,否则Spring在内部将实例化对象的时候报错;使用
赋值的,类中需要set方法
- 接口实现类
public class UserMapperImpl implements UserMapper {
SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
@Override
public List<User> queryUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.queryUser();
}
}
- Spring XML 配置文件
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/springtest?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
</bean>
<!-- SqlSessionFactoryBean-->
<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:UserMapper.xml"/>
</bean>
<!-- sqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<!-- 只能在这里使用构造器注入,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!-- 配置UserMapperImpl-->
<bean id="userMapper" class="com.huairong.mapper.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
- 测试类
public void Test() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("mybatis-dao.xml");
UserMapperImpl userMapper = context.getBean("userMapper", UserMapperImpl.class);
System.out.println(userMapper.queryUser());
}
2. 整合方式二
1、实现类继承 SqlSessionDaoSupport ,代替方式一的SqlSessionTemplate ,可直接获取SqlSession ;但SqlSessionDaoSupport 类需要 SqlSessionFactory ,所以要在将实现类注册到Spring容器中的同时,注入SqlSessionFactory 给其继承的父类
2、Spring配置的内容与方式一相比,少了注册 SqlSessionTemplate 的步骤
- 实现类
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
@Override
public List<User> queryUser() {
return getSqlSession().getMapper(UserMapper.class).queryUser();
}
}
- 配置类
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/springtest?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
</bean>
<!-- SqlSessionFactoryBean-->
<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:UserMapper.xml"/>
</bean>
<!-- 配置实现类,其继承的类需要注入sqlSessionFactory-->
<bean id="userMapper" class="com.huairong.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
- 测试类
12、声明式事务
1、搭建环境
- 接口与实现类
public interface UserMapper {
int addUser(User user);
int deleteUser(int age);
List<User> queryUser();
}
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
@Override
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
@Override
public int deleteUser(int age) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(age);
}
//将增加与删除整合到一个方法中,便于事务设置
@Override
public List<User> queryUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(new User("睡觉了", 225));
mapper.deleteUser(18);
return getSqlSession().getMapper(UserMapper.class).queryUser();
}
}
- Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.huairong.mapper.UserMapper">
<select id="queryUser" resultType="user">
select *
from user
</select>
<insert id="addUser" parameterType="user">
insert into user
values (#{name}, #{age})
</insert>
<delete id="deleteUser" parameterType="int">
delete
from user
where age =
#{age}
</delete>
</mapper>
- Spring 配置文件
<!-- 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/springtest?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
</bean>
<!-- SqlSessionFactoryBean-->
<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:UserMapper.xml"/>
</bean>
<!-- 将实现类注册到Spring容器中,为其父类注入sqlSessionFactory-->
<bean id="userMapper" class="com.huairong.mapper.UserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
- 测试
@Test
public void Test3() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("mybatis-dao.xml");
UserMapperImpl userMapper = context.getBean("userMapper", UserMapperImpl.class);
userMapper.addUser(new User("数据1", 11));
userMapper.deleteUser(25);
}
2、配置声明式事务
约束文件:aop 与 tx
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">注意点:
1、因为使用到AOP,所以动态代理的是接口,测试类中返回的也要是接口,否则报错
- Spring 配置文件
<!-- 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 结合AOP实现事务的织入-->
<!-- 配置事务通知-->
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 给哪些方法配置事务,* 代表所有-->
<!-- 配置事务的传播特性,默认为REQUIRED-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入-->
<aop:config>
<!-- 切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.huairong.mapper.*.*(..))"/>
<!-- 切入-->
<aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>
</aop:config>
- 事务传播特性
- 测试类
public void Test3() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("mybatis-dao.xml");
//注意:因为用到AOP,所以这边需要返回接口
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
userMapper.queryUser();
}