spring

本文详细介绍了Spring框架的IoC(控制反转)、AOP(面向切面编程)和DI(依赖注入)原理,包括XML配置与注解方式的实现,以及事务控制的配置方法。通过实例演示,帮助读者理解并掌握Spring在实际项目中的应用。
摘要由CSDN通过智能技术生成

1. spring的三大特性【IOC,AOP,DI】

IOC:控制反转。将创建对象的权力交给spring来处理,降低耦合。

AOP:面向切面编程。将程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对自己的已有方法进行增强。

DI:依赖注入。降低程序间的耦合

2. spring初体验

  1. 引入spring的依赖
<dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-context</artifactId>
     <version>5.0.2.RELEASE</version>
</dependency>
  1. 创建bean.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">
    <!--把对象的创建交给spring来管理-->
    <bean id="accountService" class="cn.zh.service.impl.AccountServiceImpl"></bean>
    <bean id="accountDao" class="cn.zh.dao.impl.AccountDaoImpl"></bean>
</beans>
  1. 应用
public class Client {
    /**
     * 获取spring的IOC的核心容器,并根据id获取对象
     *
     * ApplicationContext的三个常用实现类:
     *      ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在的话,加载不了。
     *      FileSystemApplicationContext:它可以加载磁盘任意路径下的配置文件(必须有访问权限)
     *      AnnotationConfigApplicationContext:它是用于读取注解创建容器的
     *
     * 核心容器的两个接口引发出的问题:
     * ApplicationContext:
     *      它在构建核心容器时,创建对象采取的策略时采用立即加载的方式。也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象
     * BeanFactory:
     *      它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候真正的创建对象
     * @param args
     */
    public static void main(String[] args) {
        //1.获取核心容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.根据id获取bean对象
        IAccountService as = (IAccountService) ac.getBean("accountService");
        IAccountDao ad = ac.getBean("accountDao",IAccountDao.class);
        System.out.println(as);
        System.out.println(ad);
    }

}

3. spring中Bean【xml方式】

  1. 创建bean的三种方式
  • 使用默认构造函数创建.在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时。采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
public class AccountServiceImpl implements IAccountService {

    @Override
    public void saveAccount() {
        System.out.println("service中的saveAccount方法执行了......");
    }

    public void init(){
        System.out.println("对象初始化了.........");
    }

    public void destroy(){
        System.out.println("对象销毁了...........");
    }
}
<!---->
<bean id="accountService" class="cn.zh.service.impl.AccountServiceImpl"></bean>
  • 使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
public class InstanceFactory {
    public IAccountService getAccountService(){
        return new AccountServiceImpl();
    }
}
<bean id="instanceFactory" class="cn.zh.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
  • 使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)
public class StaticFactory {
    public static IAccountService getAccountService(){
        return new AccountServiceImpl();
    }
}
<bean id="accountService" class="cn.zh.factory.StaticFactory" factory-method="getAccountService"></bean>
  1. bean的作用范围
bean标签的scope属性:
            作用:用于指定bean的作用范围
            取值:
                singleton:单例的(默认)
                prototype:多例的
                request:作用于web应用的请求范围
                session:作用于web应用的会话范围
                global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,它就是session
  1. bean对象的生命周期
bean对象的生命周期
        单例对象:
            出生:当容器创建时对象出生
            活着:只要容器还在,对象一直活着
            死亡:容器销毁,对象消亡
        多例对象:
            出生:当我们使用对象时spring框架为我们创建
            活着:对象只要是在使用过程中就一直活着
            死亡:当对象长时间不用,且没有别的对象引用时,由java的垃圾回收器回收
<bean id="accountService" class="cn.zh.service.impl.AccountServiceImpl"
          scope="singleton" init-method="init" destroy-method="destroy"></bean>

4. spring中的DI【xml方式】

  1. 依赖注入的简单说明
依赖注入:
            能注入的数据:
                基本类型和String
                其他bean类型(在配置文件中或者注解配置过的bean)
                复杂类型/集合类型
            注入的方式:
                使用构造函数提供
                使用set方法提供
                使用注解提供
  1. 注入方式
  • 使用构造函数提供
构造函数注入
            使用的标签:constructor-arg
            标签出现的位置:bean标签的内部
            标签中的属性:
                type:用于指定要注入的数据的数据类型,该数据也是构造函数中某个或某些参数的类型
                index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引的位置时从0开始
                name:用于指定给构造函数中指定名称的参数赋值
                ============以上三个用于指定给构造函数中的哪个参数赋值=============
                value:用于提供基本类型和String类型的数据
                ref:用于指定其他bean类型数据。她是在spring的Ioc核心容器中出现过的bean对象
public class AccountServiceImpl implements IAccountService {
    private String name;
    private Integer age;
    private Date birthday;
    public AccountServiceImpl(String name,Integer age,Date birthday){
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }
    @Override
    public void saveAccount() {
        System.out.println("service中的saveAccount方法执行了......"+name+","+age+","+birthday);
    }
}
<bean id="accountService" class="cn.zh.service.impl.AccountServiceImpl">
        <constructor-arg name="name" value="test"></constructor-arg>
        <constructor-arg name="age" value="18"></constructor-arg>
        <constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<!--配置一个日期对象-->
<bean id="now" class="java.util.Date"></bean>
  • 使用set方法提供
set方法注入
        涉及的标签:property
        出现的位置:bean标签的内部
        标签的属性:
            name:用于指定注入时所调用的set方法名称
            value:直接给值
            ref:引用其他bean对象
public class AccountServiceImpl2 implements IAccountService {
    private String name;
    private Integer age;
    private Date birthday;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public void saveAccount() {
        System.out.println("service2中的saveAccount方法执行了......"+name+","+age+","+birthday);
    }

}
<bean id="accountService2" class="cn.zh.service.impl.AccountServiceImpl2">
        <property name="name" value="test"></property>
        <property name="age"  value="18"></property>
        <property name="birthday" ref="now"></property>
</bean>
  • 使用注解提供
后边单独讲解
  1. 复杂类型注入
复杂类型的注入/集合类型的注入
        用于给List结构集合注入的标签:
            list array set
        用于给Map结构注入的标签:
            map props
        结构相同,标签可以互换
public class AccountServiceImpl3 implements IAccountService {

    private String[] myStrings;
    private List<String> myList;
    private Set<String> mySet;
    private Map<String,String> myMap;
    private Properties myProps;

    public void setMyStrings(String[] myStrings) {
        this.myStrings = myStrings;
    }

    public void setMyList(List<String> myList) {
        this.myList = myList;
    }

    public void setMySet(Set<String> mySet) {
        this.mySet = mySet;
    }

    public void setMyMap(Map<String, String> myMap) {
        this.myMap = myMap;
    }

    public void setMyProps(Properties myProps) {
        this.myProps = myProps;
    }

    @Override
    public void saveAccount() {
        System.out.println(Arrays.toString(myStrings));
        System.out.println(myList);
        System.out.println(mySet);
        System.out.println(myMap);
        System.out.println(myProps);
    }

}
<bean id="accountService3" class="cn.zh.service.impl.AccountServiceImpl3">
        <property name="myStrings">
            <array>
                <value>a</value>
                <value>b</value>
                <value>c</value>
            </array>
        </property>

        <property name="myList">
            <list>
                <value>aa</value>
                <value>bb</value>
                <value>cc</value>
            </list>
        </property>

        <property name="mySet">
            <set>
                <value>aaa</value>
                <value>bbb</value>
                <value>ccc</value>
            </set>
        </property>

        <property name="myMap">
            <map>
                <entry key="testA" value="aaaa"></entry>
                <entry key="testB" value="bbbb"></entry>
                <entry key="testC" value="cccc"></entry>
            </map>
        </property>

        <property name="myProps">
            <props>
                <prop key="testA">aaaaa</prop>
                <prop key="testB">bbbbb</prop>
                <prop key="testC">ccccc</prop>
            </props>
        </property>
</bean>

5. springIOC和DI【注解方式】

  1. bean.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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

<!--告知spring在创建容器时要扫描的包,配置所需要的标签不是在beans的约束中,而是一个context名称空间和约束中-->
    <context:component-scan base-package="cn.zh"></context:component-scan>
</beans>
  1. 创建对象的方式
* 用于创建对象的
 *      他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能时一样的
 *      Component:
 *          作用:用于把当前类对象存入spring容器中
 *          属性:
 *              value:用于指定bean的id。当我们不写时,它的默认值时当前类名,且首字母改小写
 *      Controller:一般用在表现层
 *      Service:一般用在业务层
 *      Repository:一般用在持久层
 *      以上三个注解他们的作用和属性与Component时一模一样的
 *      他们三个时spring框架为我们提供明确的的三层使用的注解,使我们的三层更加清晰
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Override
    public void saveAccount() {
        System.out.println("保存了...................");
    }
}
  1. 注入数据,作用范围,生命周期
 * 用于注入数据的
 *      他们的作用就和在xml配置文件中的bean标签中写一个<property>标签的作用时一样的
 *      Autowired:
 *          作用:自动按照类型注入,只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功
 *          出现位置:
 *              可以时变量上,也可以是方法上
 *          细节:
 *              在使用注解注入时,set方法就不是必须的了
 *
 *      Qualifier:(要和Autowired一起用)
 *          作用:在按照类中注入的基础之上再按照名称注入,它在给类成员注入时不能单独使用。但是再给方法参数注入时可以
 *          属性:
 *              value:用于指定注入bean的id
 *
 *       Resource:
 *          作用:直接按照bean的id注入,它可以独立使用
 *          属性:
 *              name:用于指定bean的id。
 *       以上三个注入都只能注入其他bean类型的数据,而基本类型和String类型无法使用上述注解实现
 *       另外,集合类型的注入只能通过XML来实现。
 *
 *       Value
 *          作用:用于注入基本类型和String类型的数据
 *          属性:
 *              value:用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
 *                     SpEL的写法:${表达式}
  * 用于改变作用范围的
 *      他们的作用集合在bean标签中使用scope属性实现的功能时一样的
 *      Scope:
 *          作用:用于指定bean的作用范围
 *          属性:
 *              value:指定范围的值。常用取值:singleton  prototype
 *
 * 和生命周期相关
 *      他们的作用和在bean标签中使用init-method和destroy-method的作用时一样的
 *      PreDestroy:
 *          作用:用于指定销毁方法
 *      PostConstruct:
 *          作用:用于指定初始化方法
@Component(value = "accountService")
public class AccountServiceImpl implements IAccountService {
//    @Autowired
//    @Qualifier(value = "accountDao")
    @Resource(name = "accountDao")
    private IAccountDao accountDao;
    @PreDestroy
    public void init(){
        System.out.println("初始化了。。");
    }
    @PostConstruct
    public void destroy(){
        System.out.println("销毁了。。。。");
    }
    @Override
    public void saveAccount() {
        accountDao.saveAccount();
    }
}

6. 自定义配置类【相当于bean.xml】

/**
 * 该类是一个配置类,它的作用和bean.xml是一样的
 * spring中的新注解
 * Configuration
 *      作用:指定当前类是一个配置类
 * ComponentScan
 *      作用:通过注解指定spring在创建容器时要扫描的包
 *      属性:
 *          value:它和basePackages的作用是一样的,都是用于指定创建容器时要扫描的包
 *                  我们使用此注解就等同于在xml中配置了:
 *                  <context:component-scan base-package="cn.zh"></context:component-scan>
 *
 * Bean
 *      作用:用于把当前方法的返回值作为bean对象存入spring的ioc容器中
 *      属性:
 *          name:用于指定bean的id。当不写时,默认值时当前方法的名称
 *      细节:
 *          当我们使用注解配置方法时,如果方法中有参数,spring框架会去容器中查找有没有可用的bean对象
 *          查找的方式和Autowired注解的作用时一样的。
 *
 * Import
 *      作用:用于导入其他的配置类
 *      属性:
 *          value:用于指定其他配置类的字节码
 *              当我们使用Import的注解之后,有Import注解的类就父配置类,而导入的都是子配置类
 *
 * PropertySource
 *      作用:用于指定properties文件的位置
 *      属性:
 *          value:指定文件的名称和路径
 *              关键字:classpath,表示类路径下
 */
@Configuration
@ComponentScan(basePackages = "cn.zh")
@PropertySource("classpath:jdbcConfig.properties")
public class SpringConfiguration {

    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    /**
     * 用来创建一个QueryRunner对象
     * @param dataSource
     * @return
     */
    @Bean(name = "runner")
    public QueryRunner createQueryRunner(@Qualifier("dataSource") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }
}

7. spring中的AOP【xml方式】

  1. 动态代理
/**
  * 动态代理:
  *      特点:字节码随用随创建,随用随加载
  *      作用:不修改源码的基础上对方法增强
  *      分类:
  *          基于接口的动态代理
  *          基于子类的动态代理
  *      基于接口的动态代理:
  *          涉及的类:Proxy
  *      如何创建代理对象:
  *          使用Proxy类中的newProxyInstance方法
  *      创建代理对象的要求:
  *          被代理类最少实现一个接口,如果没有则不能使用
  *      new ProxyInstance方法的参数:
  *          ClassLoader:类加载器
  *              它是用于加载代理对象字节码的。和被代理对象使用相同的类加载器。固定写法
  *          Class[]:
  *              它是用于让代理对象和被代理对象有相同方法。固定写法
  *          InvocationHandler:
  *              它是让我们写如何代理。我们一般都是写一个该接口的实现类,通常情况下都是匿名内部类。
  *              此接口的实现类都是谁用谁写
*/

producer类

public class Producer implements IProducer {
    /**
     * 销售
     * @param money
     */
    public void saleProduct(float money){
        System.out.println("销售产品,并拿到钱:"+money);
    }

    /**
     * 售后
     * @param money
     */
    public void afterService(float money){
        System.out.println("提供售后服务,并拿到钱:"+money);
    }

}

主体类

public class Client {
    public static void main(String[] args) {
        final Producer producer = new Producer();
        IProducer proxyProducer = (IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 作用:执行被代理对象的任何接口方法都会经过该方法
                     * @param o         代理对象的引用
                     * @param method    当前执行的方法
                     * @param objects   当前执行方法所需的参数
                     * @return          和被代理对象方法有相同的返回值
                     * @throws Throwable
                     */
                    @Override
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                        //提供增强的代码
                        Object returnValue = null;
                        //1.获取方法执行的参数
                        Float money = (Float)objects[0];
                        //2.判断当前方法是不是销售
                        if ("saleProduct".equals(method.getName())){
                            returnValue = method.invoke(producer,money*0.8f);
                        }
                        return returnValue;
                    }
                });
        proxyProducer.saleProduct(1000f);
    }

}
  1. AOP
spring中基于XML的AOP配置步骤:
        1.把通知Bean也交给spring来管理
        2.使用aop:config标签表明开始AOP配置
        3.使用aop:aspect标签表明配置切面
            id属性:是给切面提供一个唯一标识
            ref属性:是指定通知类的bean的Id
        4.在aop:aspect标签的内部使用对应标签来配置通知的类型
            我们现在示例是让printLog方法在切入点方法执行之前:所以是前置通知
            aop:before:表示配置前置通知
                method属性:用于指定Logger类中哪个方法是前置通知
                pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
            切入点表达式的写法:
                关键字:execution(表达式)
                表达式:
                    访问修饰符  返回值  包名.包名.包名...类名.方法名(参数列表)
                标准的表达式写法:
                    public void cn.zh.service.impl.AccountServiceImpl.saveAccount()
                范围修饰符可以省略
                    void cn.zh.service.impl.AccountServiceImpl.saveAccount()
                返回值可以使用通配符,表示任意返回值
                    * cn.zh.service.impl.AccountServiceImpl.saveAccount()
                包名可以使用通配符,表示任意包,但是有几级包,就需要几个*
                    * *.*.*.*.AccountServiceImpl.saveAccount()
                包名可以使用..表示当前包及其子包
                    * *..AccountServiceImpl.saveAccount()
                类名和方法名都可以使用*进行通配
                    * *..*()
                参数列表:
                    可以直接写数据类型:
                        基本类型直接写名称           int
                        引用类型写包名.类名的方式       java.lang.String
                    可以使用通配符表示任意类型,但必须有参数
                    可以使用..表示有无参数均可
                全通配写法:
                    * *..*.*(..)
                实际开发中切入点表达式的通常写法:
                    切到业务层实现类下的所有方法
                        * cn.zh.service.impl.*.*(..)
public class Logger {
    /**
     * 前置通知
     */
    public void beforePrintLog(){
        System.out.println("前置通知Logger类中的printLog方法开始记录日志了.......");
    }

    /**
     * 后置通知
     */
    public void afterReturningPrintLog(){
        System.out.println("后置通知Logger类中的printLog方法开始记录日志了.......");
    }

    /**
     * 异常通知
     */
    public void afterThrowingPrintLog(){
        System.out.println("异常通知Logger类中的printLog方法开始记录日志了.......");
    }

    /**
     * 最终通知
     */
    public void afterPrintLog(){
        System.out.println("最终通知Logger类中的printLog方法开始记录日志了.......");
    }

}

public class AccountServiceImpl implements IAccountService {

    public void saveAccount() {
        System.out.println("保存了。。。。。。。");
    }

    public void updateAccount(int i) {
        System.out.println("更新了。。。。。。。");
    }

    public int deleteAccount() {
        System.out.println("删除了。。。。。。。。");
        return 0;
    }
}
<!--配置spring的ioc,把service对象配置进来-->
<bean id="accountService" class="cn.zh.service.impl.AccountServiceImpl"></bean>

<!--配置Logger类-->
<bean id="logger" class="cn.zh.utils.Logger"></bean>

<!--配置AOP-->
<aop:config>
    <!--配置切入点表达式,id属性用于指定表达式的唯一标识。expression属性用于指定表达式内容
    此标签写在aop:aspect标签内部只能当前切面使用。
    它还可以写在aop:aspect外面,此时就变成了所有切面可用。
    -->
    <aop:pointcut id="pt1" expression="execution(* cn.zh.service.impl.*.*(..))"/>

    <!--配置切面-->
    <aop:aspect id="logAdvice" ref="logger">
        <!--配置前置通知:在切入点方法执行之前-->
        <aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>
        <!--配置后置通知:在切入点方法正常执行之后-->
        <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
        <!--配置异常通知:在切入点方法执行产生异常之后执行-->
        <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
        <!--配置最终通知:无论切入点方法是否正常执行它都会在其后面执行-->
        <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
    </aop:aspect>

</aop:config>

8. spring中的AOP【注解方式】

  1. 开启注解支持
<?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"
       xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        
    <!--配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="cn.zh"></context:component-scan>
    
    <!--配置spring开启注解aop的支持-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
  1. Logger类
@Component("logger")
@Aspect//表示当前类是一个切面
public class Logger {
    @Pointcut("execution(* cn.zh.service.impl.*.*(..))")
    private void pt1(){}
    /**
     * 前置通知
     */
    @Before("pt1()")
    public void beforePrintLog(){
        System.out.println("前置通知Logger类中的printLog方法开始记录日志了.......");
    }

    /**
     * 后置通知
     */
    @AfterReturning("pt1()")
    public void afterReturningPrintLog(){
        System.out.println("后置通知Logger类中的printLog方法开始记录日志了.......");
    }

    /**
     * 异常通知
     */
    @AfterThrowing("pt1()")
    public void afterThrowingPrintLog(){
        System.out.println("异常通知Logger类中的printLog方法开始记录日志了.......");
    }

    /**
     * 最终通知
     */
    @After("pt1()")
    public void afterPrintLog(){
        System.out.println("最终通知Logger类中的printLog方法开始记录日志了.......");
    }

}

9. spring中的事务控制【xml方式】

  1. 引入依赖
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
</dependency>
  1. xml配置步骤
spring中基于XML的声明式事务控制配置步骤
        1.配置事务管理器
        2.配置事务通知
               此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop的
               使用tx:advice标签配置事务通知
                    属性:
                        id:给事务通知起一个唯一标识
                        transaction-manager:给事务通知提供一个事务管理器引用
        3.配置AOP中的通用切入点表达式
        4.建立事务通知和切入点表达式的对应关系
        5.配置事务的属性
            是在事务的通知tx:advice标签的内部
<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置service-->
    <bean id="accountService" class="cn.zh.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置dao-->
    <bean id="accountDao" class="cn.zh.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>


     <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=GMT%2B8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--配置事务的属性
            isolation:用于指定事务的隔离级别。默认值时DEFAULT,表示使用数据库的默认隔离级别。
            no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚
            propagation:用于指定事务的传播行为。默认值时REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
            read-only:用于指定事务是否只读,只有查询方法才能设置为true。默认值时false
            rollback-for:用于指定一个异常,当产生该异常时,事务回滚,没有默认值。表示任何异常都回滚
            timeout:用于指定事务的超时时间,默认值时-1,表示永不超时。单位(秒)
        -->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>
    <!--配置aop-->
    <aop:config>
        <!--配置切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* cn.zh.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

</beans>

10. spring中的事务控制【注解方式】

  1. 配置步骤
spring中基于XML的声明式事务控制配置步骤
        1.配置事务管理器
        2.开启spring对注解事务的支持
        3.在需要事务支持的地方使用@Transaction注解
<?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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!---->
    <context:component-scan base-package="cn.zh"></context:component-scan>

    <!--配置jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>


     <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/ssm?serverTimezone=GMT%2B8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

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

</beans>
  1. 业务层编写控制
/**
 *
 *
 * 账户控制在业务层
 */
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    public Account findAccountById(Integer accountId) {
            return accountDao.findAccountById(accountId);
    }

    /**
     * 转账
     * @param sourceName
     * @param targetName
     * @param money
     */
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = false)
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
                //1.根据名称查询转出账户
                Account source = accountDao.findAccountByName(sourceName);
                //2.根据名称查询转入账户
                Account target = accountDao.findAccountByName(targetName);
                //3.转出账户减钱
                source.setMoney(source.getMoney()-money);
                //4.转入账户加钱
                target.setMoney(target.getMoney()+money);
                int i=1/0;
                //5.更新转出账户
                accountDao.updateAccount(source);
                //6.更新转入账户
                accountDao.updateAccount(target);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值