官网:https://spring.io/projects/spring-framework#overview
总结一句话:Spring就是一个轻量级的控制反转(IOC)和面向切面编程(AOP)的框架!
弊端:发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱!”
现代化的Java开发,说白了就是基于Spring的开发!
public interface UserDao {
public void getUser();
}
public class UserDaoImpl implements UserDao {
public void getUser() {
System.out.println("默认获取用户的数据");
}
}
public class UserDaoOracleImpl implements UserDao {
public void getUser() {
System.out.println("Oracle获取用于数据!");
}
}
public interface UserService {
public void getUser();
}
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果代码量十分大,修改一次的成本代价十分昂贵!
我们使用一个Set接口实现,已经发生了革命性的变化!
// 利用set进行实现动态值的注入!
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
这种思想,从本质上解决了问题,我们程序员不用再去管理对象的创建了。系统的耦合性大大降低,可以更加专注在业务的实现上!这是IOC的原型!
控制反转IOC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IOC的一种方法,也有人认为Dl只是IOC的另一种说法。没有IOC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是IOC容器,其实现方法是依赖注入(Dependency Injection,DI)。
注:spring需要导入commons-logging进行日志记录,我们利用maven,它会自动下载对应的依赖项
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
编写一个Hello实体类
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 + ‘\‘‘ +
‘}‘;
}
}
编写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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--bean就是java对象,有spring创建和管理-->
<bean id="hello" class="com.mc.pojo.Hello">
<property name="name" value="Spring"/>
</bean>
</beans>
进行测试
public class MyTest {
public static void main(String[] args) {
// 获取Spring的上下文对象
// 解析beans.xml文件,生成管理相应的Bean对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 我们的对象现在都在Spring中管理了,我们要使用,直接去里面取出来就可以!
// getBean:参数即为spring配置文件中bean的id
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
<bean id="mysqlImpl" class="com.mc.pojo.UserDaoMysqlImpl"/>
<bean id="oracleImpl" class="com.mc.pojo.UserDaoOracleImpl"/>
<bean id="UserServiceImpl" class="com.mc.service.UserServiceImpl">
<!--
ref: 引用Spring容器中创建好的对象
value: 具体的值,基本数据类型
-->
<property name="userDao" ref="mysqlImpl"/>
</bean>
// 获取ApplicationContext 拿到Spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 容器在手,天下我有,需要什么,就直接get什么
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
Hello对象是谁创建的?
Hello 对象的属性是怎么设置的?
这个过程就叫控制反转︰
<bean id="user" class="com.mc.pojo.User">
<property name="name" value="MC"/>
</bean>
<bean id="user" class="com.mc.pojo.User">
<constructor-arg index="0" value="狂神说Java"/>
</bean>
<bean id="user" class="com.mc.pojo.User">
<constructor-arg type="java.lang.String" value="qinjiang"/>
</bean>
<bean id="user" class="com.mc.pojo.User">
<constructor-arg name="name" value="狂神"/>
</bean>
总结:在配置文件加载的时候,容器中管理的对象(bean)就已经初始化了!
<!--别名,如果添加了别名,我们也可以使用别名获取到这个对象-->
<alias name="user" alias="userNew"/>
<!--
id: bean的唯一标识符,也就是相当于我们学的对象名
class: bean对象所对应的全限定名: 包名 + 类型
name: 也是别名,而且name可以同时取多个别名
-->
<bean id="userT" class="com.mc.pojo.UserT" name="userT2 u2,u3;u4">
<property name="name" value="西部开源"/>
</bean>
这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!
<import resource="beans.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>
使用的时候,直接使用总的配置就可以了
之前分析过,见5.1~5.2
【环境搭建】
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> card;
private Set<String> games;
private String wife;
private Properties info;
}
3.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.mc.pojo.Student">
<!--第一种,普通值注入,直接使用value-->
<property name="name" value="秦疆"/>
</bean>
</beans>
4.测试类
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getAddress());
}
}
完善注入信息
<?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.mc.pojo.Address">
<property name="address" value="西安"/>
</bean>
<bean id="student" class="com.mc.pojo.Student">
<!--第一种,普通值注入直接使用value-->
<property name="name" value="秦疆"/>
<!--第二种,bean注入,使用ref-->
<property name="address" ref="address"/>
<!--第三种,数组注入,使用array-->
<property name="books">
<array>
<value>红楼梦</value>
<value>水浒传</value>
<value>三国演义</value>
<value>西游记</value>
</array>
</property>
<!--第四种,List注入,使用list-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>敲代码</value>
<value>看电影</value>
</list>
</property>
<!--第五种,Map注入,使用map-->
<property name="card">
<map>
<entry key="身份证" value="231231231231231"/>
<entry key="银行卡" value="156436465231311"/>
</map>
</property>
<!--第六种,Set注入,使用set-->
<property name="games">
<set>
<value>LOL</value>
<value>COC</value>
<value>BOB</value>
</set>
</property>
<!--第七种,null注入,使用null-->
<property name="wife">
<null/>
</property>
<!--第八种,Properties注入,使用props-->
<property name="info">
<props>
<prop key="学号">20210812</prop>
<prop key="姓名">小李</prop>
<prop key="性别">男</prop>
</props>
</property>
</bean>
</beans>
我们可以使用p命名空间和c命名空间进行注入
官方解释:
使用!
<?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">
<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="com.mc.pojo.User" p:name="狂神" p:age="18"/>
<!--c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.mc.pojo.User" c:name="秦疆" c:age="20"/>
</beans>
测试:
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);
System.out.println(user);
}
注意点:p命名和c命名空间不能直接使用,需要导入xml约束!
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
单例模式(Spring默认机制)
<bean id="user" class="com.mc.pojo.User" p:name="狂神" p:age="18" scope="singleton"/>
原型模式:每次从容器中get的时候,都会产生一个新对象!
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
其余的request、session、application、websocket,这些个只能在web开发中使用到!
在Spring中有三种自动装配的方式
环境搭建:一个人有两个宠物!
<!--
byName: 会自动在容器上下文中查找和自己对象set方法后面的值对应的beanid
-->
<bean id="people" class="com.mc.pojo.People" autowire="byName">
<property name="name" value="小狂神"/>
</bean>
<!--
byName: 会自动在容器上下文中查找和自己对象set方法后面的值对应的beanid
byType: 会自动在容器上下文中查找和自己对象属性类型相同的bean
-->
<bean id="people" class="com.mc.pojo.People" autowire="byType">
<property name="name" value="小狂神"/>
</bean>
小结:
jdk1.5支持的注解,Spring2.5就支持注解了!
The introduction of annotation-based configuration raised the question of whether this approach is “better" than 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/>
</beans>
@Autowired
直接在属性上使用即可!也可以在set方式上使用!
使用Autowired 我们可以不用编写Set方法了,前提是你这个自动装配的属性在lOC (Spring)容器中存在,且符合名字byname!
科普:
@Nullable 字段标记了这个注解,说明这个字段可以为null
public @interface Autowired {
boolean required() default true;
}
测试代码
public class People {
@Autowired
private Dog dog;
// 如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
@Autowired(required = false)
private Cat cat;
private String name;
}
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一个唯一的bean对象注入!
public class People {
@Autowired
@Qualifier(value = "dog11")
private Dog dog;
@Autowired
@Qualifier(value = "cat11")
private Cat cat;
private String name;
}
@Resource注解
public class People {
@Resource
private Dog dog;
@Resource(name = "cat2")
private Cat cat;
}
小结:
@Resource 和@ Autowired 的区别:
在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"
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>
bean
属性如何注入
// 等价于<bean id="user" class="com.mc.pojo.User"/>
// @Component: 组件
@Component
public class User {
public String name;
// 相当于 <property name="name" value="小马"/>
@Value("小马")
public void setName(String name) {
this.name = name;
}
}
衍生的注解
@Component 有几个衍生注解,我们在web开发中,会按照MVC三层架构分层!
dao 【@Repository】
service 【@Service】
controller
这四个注解功能都是一样的,都是代表将某个类注册到Spring中,装配Bean
自动装配置
@Autowired:自动装配通过类型。名字
如果Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value="xxx")
@Nullable字段标记了这个注解,说明这个字段可以为null
@Resource:自动装配通过名字、类型
作用域
@Component
@Scope("prototype")
public class User {
public String name;
// 相当于 <property name="name" value="小马"/>
@Value("小马")
public void setName(String name) {
this.name = name;
}
}
小结
xml与注解:
xml更加万能,适用于任何场合!维护简单方便。
注解不是自己类使用不了,维护相对复杂!
xml与注解的最佳实践:
xml用来管理bean
注解只负责完成属性的注入
我们在使用的过程中,只需要注意一个问题:必须让注解生效,就需要开启注解的支持
<!--指定要扫描的包,这个包下的注解就会生效-->
<context:component-scan base-package="com.mc"/>
<context:annotation-config/>
我们现在要完全不使用Spring的xml配置了,全权交给Java来做!
JavaConfig 是Spring的一个子项目,在Spring 4 之后,它成为了一个核心功能!
实体类
// 这里这个注解的意思,就是说这个类被Spring接管了,注册到了容器中
@Component
public class User {
public String name;
@Value("狂神") // 属性注入值
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" +
"name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
配置文件
// 这个也会被Spring容器托管,注册到容器中,因为它本来就是一个@Component
// @Configuration代表这是一个配置类,就和我们之前的beans.xml是一样的
@Configuration
@ComponentScan("com.mc.pojo")
@Import(MyConfig2.class)
public class MyConfig {
// 注册一个bean,就相当于我们之前写的一个bean标签
// 这个方法的名字,就相当于bean标签中的id属性
// 这个方法的返回值,就相当于bean标签中的class属性
@Bean
public User user(){
return new User(); // 就是返回要注入到bean的对象!
}
}
测试类
public class MyTest {
public static void main(String[] args) {
// 如果完全使用了配置类方法去做,我们就只能通过AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User getUser = (User) context.getBean("user");
System.out.println(getUser.getName());
}
}
这种纯Java的配置方式,在SpringBoot中随处可见!
为什么要学习代理模式?因为这就是SpringAOP的底层!【SpringAOP 和 SpringMVC】
代理模式的分类:
角色分析:
实现步骤:
接口
// 租房
public interface Rent {
public void rent();
}
真实角色
// 房东
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租房子!");
}
}
代理角色
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
public void rent() {
seeHouse();
host.rent();
hetong();
fare();
}
// 看房
public void seeHouse(){
System.out.println("中介带你看房!");
}
// 看房
public void hetong(){
System.out.println("签租赁合同!");
}
// 收中介费
public void fare(){
System.out.println("收中介费!");
}
}
客户端访问代理角色
public class Client {
public static void main(String[] args) {
// 房东要租房子
Host host = new Host();
// 代理,中介帮房东租房子,但是呢,代理角色会有一些附属操作
Proxy proxy = new Proxy(host);
// 你不用面对房东,直接找中介租房即可
proxy.rent();
}
}
代理模式的好处:
缺点:
代码实现:
接口
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
真实角色
// 真实对象
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("查询了一个用户!");
}
}
代理角色
public class UserServiceProxy implements UserService {
private UserServiceImpl userService;
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
public void add() {
log("add");
userService.add();
}
public void delete() {
log("delete");
userService.delete();
}
public void update() {
log("update");
userService.update();
}
public void query() {
log("query");
userService.query();
}
// 日志方法
public void log(String msg){
System.out.println("【Debug】使用了"+msg+"方法!");
}
}
客户端访问代理角色
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy();
proxy.setUserService(userService);
proxy.add();
}
}
聊聊AOP
需要了解两个类:Proxy:代理,InvocationHandler:调用处理程序
动态代理的好处:
代码实现:
动态生成代理类
// 我们会用这个类自动生成代理类
public class ProxylnvocationHandler implements InvocationHandler {
// 被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
// 生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
// 处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
// 动态代理的本质,就是使用反射机制实现!
Object result = method.invoke(target, args);
return result;
}
public void log(String msg){
System.out.println("执行了"+msg+"方法!");
}
}
客户端访问代理角色
public class Client {
public static void main(String[] args) {
// 真实角色
UserServiceImpl userService = new UserServiceImpl();
// 代理角色,不存在
ProxylnvocationHandler pih = new ProxylnvocationHandler();
// 设置要代理对象
pih.setTarget(userService);
// 动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.query();
}
}
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AoP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
提供声明式事务,允许用户自定义切面
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
即AOP在不改变原有代码的情况下,去增加新的功能
【重点】使用AOP之前,需要导入一个依赖包
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
方式一:使用Spring的 API 接口 【主要是SpringAPI接口实现】
方式二:自定义类来实现AOP 【主要是切面定义】
方式三:使用注解实现
<?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-->
<bean id="userService" class="com.mc.service.UserServiceImpl"/>
<bean id="beforeLog" class="com.mc.log.BeforeLog"/>
<bean id="afterLog" class="com.mc.log.AfterLog"/>
<!--方式一: 使用原生的Spring API接口-->
<!--配置aop: 需要导入aop的约束-->
<!--<aop:config>
<!–切入点: expression表达式,execution(要执行的位置)–>
<aop:pointcut id="pointcut" expression="execution(* com.mc.service.UserServiceImpl.*(..))"/>
<!–执行环绕增加–>
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>-->
<!--方式二: 自定义类-->
<!-- <bean id="diy" class="com.mc.diy.DiyPointCut"/>
<aop:config>
<!–自定义切面,ref 要引用的类–>
<aop:aspect ref="diy">
<!–切入点–>
<aop:pointcut id="point" expression="execution(* com.mc.service.UserServiceImpl.*(..))"/>
<!–通知–>
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>-->
<!--方式三: 使用注解-->
<bean id="annotationPointCut" class="com.mc.diy.AnnotationPointCut"/>
<!--开启注解支持 JDK(默认 proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy proxy-target-class="false"/>
</beans>
步骤:
<dependencies>
<!-- junit驱动 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!-- mybatis驱动 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<!--Spring操作数据库的话,还需要一个spring-jdbc包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
编写配置文件
测试
编写数据源配置
<!--DataSource: 使用Spring的数据源替换Mybatis的配置
我们这里使用Spring提供的JDBC: org.springframework.jdbc.datasource
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true"/>
<property name="username" value="root"/>
<property name="password" value="mc123456"/>
</bean>
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/mc/mapper/*.xml"/>
</bean>
sqlSessionTemplate
<!--SqlSessionTemplate: 就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
需要给接口加实现类
public class UserMapperImpl implements UserMapper {
// 我们所有的操作,在原来都使用sqlSession来执行,现在都使用SqlSessionTemplate
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
将自己写的实现类,注入到Spring中
<bean id="userMapper" class="com.mc.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
测试使用即可!
事务ACID原则:
声明式事务:AOP
<!--配置声明式事务-->
<bean id="transactionManage" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManage">
<!--给哪些方法配置事务-->
<!--配置事务的传播特性: propagation-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.mc.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
编程式事务:需要在代码中进行事务的管理
思考:为什么需要事务?
原文:https://www.cnblogs.com/mc-blog/p/15139093.html