spring_IOC AOP 事物管理

《尚硅谷》

一:spring:Helloworld

Spring 是轻量级的开源的 JavaEE 框架,基本组成如下:

01.新建项目之后,建lib目录。引入jar包,只需要引入最基本的包

02.在src中建立普通类

package com.atguigu.spring5;
//添加一个add方法
public class User {
    public void add()
    {
        System.out.println("add.....");
    }
}

03.建立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 id="user" class="com.atguigu.spring5.User"></bean>
</beans>

04.建立测试类进行测试

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void test()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        User user=context.getBean("user", User.class);
        System.out.println(user);
        user.add();
    }
}

05输出结果:

在这里插入图片描述

二:spring:IOC

1、什么是 IOC

(1)控制反转,把对象创建和对象之间的调用过程,交给 Spring 进行管理

(2)使用 IOC 目的:为了耦合度降低 (3)做入门案例就是 IOC 实现

2、 IOC 底层原理 (1) xml 解析、工厂模式、反射

2、 Spring 提供 IOC 容器实现两种方式:(两个接口)

(1) BeanFactory: IOC 容器基本实现,是 Spring 内部的使用接口,不提供开发人员进行使用 * 加载配置文件时候不会创建对象,在获取对象(使用)才去创建对象

(2) ApplicationContext: BeanFactory 接口的子接口,提供更多更强大的功能,一般由开发人 员进行使用 * 加载配置文件时候就会把在配置文件对象进行创建

3.IOC的beans管理:创建对象与属性注入 有两种实现方式,(1)基于 xml 配置文件方式实现 (2)基于注解方式实现

01.IOC依赖注入:第一种注入方式:使用 set 方法进行注入

1 创建类,并且设置set方法

package com.atguigu.spring5;
 public class Book {
        //创建属性
        private String bname;
        private String bauthor;
        //创建属性对应的 set 方法
        public void setBname(String bname) {
            this.bname = bname;
        }
        public void setBauthor(String bauthor) {
            this.bauthor = bauthor;
        }
    }

2.xml中配置

<bean id="book" class="com.atguigu.spring5.Book">
        <property name="bname" value="红楼"></property>
        <property name="bauthor" value="曹雪芹"></property>
    </bean>

3.测试

public class testspring5
{
    @Test
    public void test()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        /*User user=context.getBean("user", User.class);
        System.out.println(user);
        user.add();*/
        Book book=context.getBean("book",Book.class);
        book.set();
    }
}

02.IOC依赖注入:第一种注入方式:使用 set 方法进行注入

1 创建类,并且设置有参构造

public class Orders
{
    private String oname;
    private String address;
    //有参数构造
    public Orders(String oname,String address) {
        this.oname = oname;
        this.address = address;
    }
}

2.xml配置

<bean id="orders" class="com.atguigu.spring5.Orders">
        <constructor-arg name="oname" value="kk"></constructor-arg>
        <constructor-arg name="address" value="cc"></constructor-arg>
    </bean>

3.测试

03、注入属性-外部 bean

1.建立两个类 service 类和 dao 类

package com.atguigu.spring5.dao;

public interface UserDao {
    public void update();
}
package com.atguigu.spring5.dao;

public class UserDaoImpl implements UserDao {

    @Override
    public void update() {
        System.out.println("dao update...........");
    }
}

建立service

package com.atguigu.spring5.Service;

import com.atguigu.spring5.dao.UserDao;

public class UserService
{
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void add() {
        System.out.println("service add...............");
        userDao.update();
    }
}

2.xml 配置

    <bean id="userService" class="com.atguigu.spring5.Service.UserService">
        <property name="userDao" ref="userDaoImpl"></property>
    </bean>
    <bean id="userDaoImpl" class="com.atguigu.spring5.dao.UserDaoImpl"></bean>

3.测试

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void test()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
        UserService userService=context.getBean("userService", UserService.class);
        userService.add();
    }
}

04.集合等属性的xml注入

1。建立类:

package com.atguigu.spring5.dao;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Stu
{
    private String[] courses;
    //2 list 集合类型属性
    private List<String> list;
    //3 map 集合类型属性
    private Map<String,String> maps;
    //4 set 集合类型属性
    private Set<String> sets;
    public void setSets(Set<String> sets) {
        this.sets = sets;
    }
    public void setCourses(String[] courses) {
        this.courses = courses;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
}

2.xml注入

 <bean id="stu" class="com.atguigu.spring5.dao.Stu">
    <!--数组类型属性注入-->
    <property name="courses">
        <array>
            <value>java 课程</value>
            <value>数据库课程</value>
        </array>
    </property>
    <!--list 类型属性注入-->
    <property name="list">
    <list>
        <value>张三</value>
        <value>小三</value>
    </list>
    </property>
        <!--map 类型属性注入-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>
        <!--set 类型属性注入-->
        <property name="sets">
            <set>
                <value>MySQL</value>
                <value>Redis</value>
            </set>
        </property>
    </bean>

05. IOC 操作 Bean 管理(FactoryBean)

01.建立基本类

public class Course {
 public void setCname( String name)
 {
     System.out.println(name);
 }
}

02.工厂类

import org.springframework.beans.factory.FactoryBean;

public class MyBean implements FactoryBean<Course> {
    //定义返回 bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("abc");
        return course;
    }
    @Override
    public Class<?> getObjectType() {
        return null;
    }
    @Override
    public boolean isSingleton() {
        return false;
    }
}

03.xml配置

 <bean id="myBean" class="com.atguigu.spring5.dao.MyBean">
    </bean>

04.测试

public void test3() {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean3.xml");
Course course = context.getBean("myBean", Course.class);
System.out.println(course);
}

06. IOC 操作 Bean 管理(bean 作用域)

1)在 spring 配置文件 bean 标签里面有属性( scope)用于设置单实例还是多实例

(2) scope 属性值 第一个值 默认值, singleton,表示是单实例对象 第二个值 prototype,表示是多实例对象

07.演示 bean 生命周期

public Orders() {
        System.out.println("第一步 执行无参数构造创建 bean 实例");
    }
    private String oname;
    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步 调用 set 方法设置属性值");
    }
    //创建执行的初始化的方法
    public void initMethod() {
        System.out.println("第三步 执行初始化的方法");
    }
    //创建执行的销毁的方法
    public void destroyMethod() {
        System.out.println("第五步 执行销毁的方法");
    }

xml配置

 <bean id="orders" class="com.atguigu.spring5.dao.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"></property>
    </bean>

测试方法:

@Test
    public void testBean3() {
// ApplicationContext context =
// new ClassPathXmlApplicationContext("bean4.xml");
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("第四步 获取创建 bean 实例对象");
        System.out.println(orders);
//手动让 bean 实例销毁
        context.close();
    }

(1)通过构造器创建 bean 实例(无参数构造)

(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)

(3)把 bean 实例传递 bean 后置处理器的方法 postProcessBeforeInitialization

(4)调用 bean 的初始化的方法(需要进行配置初始化的方法)

( 5)把 bean 实例传递 bean 后置处理器的方法 postProcessAfterInitialization

(6) bean 可以使用了(对象获取到了)

(7)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

07. IOC 操作 Bean 管理(基于注解方式)

01.引入AOP.jar,注解开通自动扫描

<context:component-scan base-package="com.atguigu.spring5.auto"></context:component-scan>

02.创建普通类,添加注释

Spring 针对 Bean 管理中创建对象提供注解

(1) @Component

(2) @Service

(3) @Controller

(4) @Repository

package com.atguigu.spring5.auto;

import org.springframework.stereotype.Component;

@Component(value="service")//<bean id="userService" class=".."/>
public class Service {
    public void add() {
        System.out.println("service add.......");
    }
}

03.建立测试类

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void testBean3() {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        Service service=context.getBean("service",Service.class);
        service.add();
    }
}

三.spring:AOP

1、 AOP 底层使用动态代理

(1) 第一种 有接口情况,使用 JDK 动态代理 ⚫ 创建接口实现类代理对象,增强类的方法

(2) 第二种 没有接口情况,使用 CGLIB 动态代理

2.JDK 动态代理

01.创建接口和普通类

package com.atguigu.spring5.auto;

public interface UserDao {
    public int add(int a,int b);
    public String update(String id);
}
package com.atguigu.spring5.auto;

public class UserDaoImpl implements UserDao {
    @Override
    public int add(int a, int b) {
        return a+b;
    }
    @Override
    public String update(String id) {
        return id;
    }
}

02.创建代理类


public class JDKProxy {
    public static void main(String[] args) {
//创建接口实现类代理对象
 Class[] interfaces = {UserDao.class};
 UserDaoImpl userDao = new UserDaoImpl();
UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int result = dao.add(1, 2);
        System.out.println("result:"+result);
    }
}
//创建代理对象代码
class UserDaoProxy implements InvocationHandler {
    //1 把创建的是谁的代理对象,把谁传递过来
//有参数构造传递
    private Object obj;
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }
    //增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws
            Throwable {
//方法之前
        System.out.println("方法之前执行...."+method.getName()+" :传递的参数..."+ Arrays.toString(args));
//被增强的方法执行
        Object res = method.invoke(obj, args);
//方法之后
        System.out.println("方法之后执行...."+obj);
        return res;
    }
}

3.基于 AspectJ 实现 AOP 操作

(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强

(2)语法结构: execution([权限修饰符] [返回类型] [类全路径] 方法名称 )

举例 1:对 com.atguigu.dao.BookDao 类里面的 add 进行增强 execution(* com.atguigu.dao.BookDao.add(…))

举例 2:对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强 execution(* com.atguigu.dao.BookDao.* (…))

01.新建普通类和增强方法类

package com.atguigu.spring5.auto;

import org.springframework.stereotype.Component;

//添加一个add方法
@Component
public class User {
    public void add()
    {
        System.out.println("add.....");
    }
}
package com.atguigu.spring5.auto;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class UserProxy {
    @Before(value = "execution(* com.atguigu.spring5.auto.User.add(..))")
    public void before() {//前置通知
        System.out.println("before......");
    }
}

02.xml中开启扫描和aop

 <context:component-scan base-package="com.atguigu.spring5.auto"></context:component-scan>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

03.测试

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.auto.Service;
import com.atguigu.spring5.auto.User;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void testBean3() {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        User user=context.getBean("user",User.class);
        user.add();
    }
}

有多个增强类多同一个方法进行增强,设置增强类优先级

(1)在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

@Component

@Aspect

@Order(1)

public class PersonProxy

四.spring 事务

(1)事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操 作都失败

(2)典型场景:银行转账 * lucy 转账 100 元 给 mary * lucy 少 100, mary 多 100 2、事务四个特性(ACID)

(1)原子性

(2)一致性

(3)隔离性

(4)持久性

01.搭建事物基本环境

01.新建UserDao接口以及实现类

package com.atguigu.spring5.dao;

public interface UserDao
{
    public void reduceMoney();
    public void addMoney();
}

package com.atguigu.spring5.dao;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //lucy 转账 100 给 mary
//少钱
    @Override
    public void reduceMoney() {
        String sql = "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql,100,"lucy");
    }
    //多钱
    @Override
    public void addMoney() {
        String sql = "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    }
}

02.service类和测试方法

package com.atguigu.spring5.Service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;
    //转账的方法
    public void accountMoney() {
//lucy 少 100
        userDao.reduceMoney();
//mary 多 100
        userDao.addMoney();
    }
}
package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.Service.UserService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class testspring5
{
    @Test
    public void testBean3() {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");
        UserService userService=context.getBean("userService",UserService.class);
        userService.accountMoney();
    }
}

03.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"
       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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    <context:component-scan base-package="com.atguigu.spring5"></context:component-scan>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql:///springtest?serverTimezone=GMT" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
        <property name="driverClassName" value=" com.mysql.cj.jdbc.Driver" />
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入 dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

04.测试可以看到数据库中的变化:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eSZeADN3-1632797441202)(C:\Users\123\AppData\Roaming\Typora\typora-user-images\1632795388631.png)]

05.修改上面的service模拟出现异常的情况

package com.atguigu.spring5.Service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;
    //转账的方法
    public void accountMoney() {
//lucy 少 100
        try {
            userDao.reduceMoney();
            int i=10/0;//异常出现
            userDao.addMoney();
        }
        catch (Exception e)
        {

        }

//mary 多 100

    }
}

06…测试,可以看到测试的结果如下:

在这里插入图片描述

02.事物操作

在 Spring 进行声明式事务管理,底层使用 AOP 原理

01.xml配置

  <!--创建事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

02.修改Service类

在 service 类上面( 或者 service 类里面方法上面)添加事务注解

(1) @Transactional,这个注解添加到类上面,也可以添加方法上面

(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务

(3)如果把这个注解添加方法上面,为这个方法添加事务

package com.atguigu.spring5.Service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
 @Transactional(propagation = Propagation.REQUIRED)
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;
    //转账的方法

    public void accountMoney() {
//lucy 少 100
            userDao.reduceMoney();
            int i=10/0;//异常出现
            userDao.addMoney();
//mary 多 100
    }
}

03.测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-17yi3xcn-1632797441204)(C:\Users\123\AppData\Roaming\Typora\typora-user-images\1632797075017.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mS2L5cCt-1632797441205)(C:\Users\123\AppData\Roaming\Typora\typora-user-images\1632797084290.png)]

03.事物的传播行为

在这里插入图片描述在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值