Spring

文章目录

一、Spring

1)概述

1、Spring是轻量级的开源的JavaEE框架
2、Spring可以解决企业应用开发的复杂性
3、Spring有两个核心部分:IOC和AOP
	1)IOC:控制反转,把创建对象的过程交给Spring进行管理
	2)AOP:面向切面,不修改源代码进行功能增强
4、Spring特点:
	1)方便解耦,简化开发
	2)AOP编程的支持
	3)声明式事务的支持
	4)方便程序的测试
	5)方便和其他框架进行整合
	6)降低Java EE API的使用难度
	7)Java 源码是经典学习范例

2)Spring入门

  1. 创建Java项目,并导入jar包

  2. 创建普通类,在这个类创建普通方法

package org.example.domain;

public class User {
    public void add(){
        System.out.println("hello Spring");
    }
}
  1. 创建Spring配置文件,在配置文件配置创建的对象
	1)Spring配置文件使用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">

    <!--配置User对象的创建-->
    <bean id="user" class="org.example.domain.User"></bean>
</beans>
  1. 测试代码
package org.example.testdome;

import org.example.domain.User;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring01 {
    @Test
    public void testAdd(){
//        1、加载Spring配置文件
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean01.xml");
//        2、获取配置创建对象
        User user = applicationContext.getBean("user", User.class);
        System.out.println(user);
        user.add();
    }
}

3)IOC容器

1.IOC底层原理

1.什么是IOC
	1)控制反转:把对象的创建和对象之间的调用过程,交给Spring进行管理
	2)目的:解耦
	3)入门案例就是IOC实现
2.IOC底层原理
	1)xml解析,工厂模式,反射

IOC过程

1)第一步:xml配置文件,配置创建的对象
    <bean id="user" class="org.example.domain.User"></bean>
2)第二步:有Service类和dao类,创建工厂
class UserFactory{
	public static UserDao getDao(){
		String classValue = class属性值;//xml解析
		Class class = Class.forName(classValue);//通过反射创建对象
		return (UserDao)class/newInstance();
	}
}

2.IOC接口(Bean Factory)

1)IOC思想基于IOC容器完成,IOC容器底层就是对象工厂
2Spring提供IOC容器实现两种方式:(两个接口)
	1BeanFactory:IOC容器基本实现,是Spring内部的使用接口,不提供开发人员进行使用
	/*加载配置文件时候不会创建对象,在获取/使用对象的时候才会创建对象*/
	
	2ApplicationContextBeanFactory皆空的子接口,,提供更多更强大的功能,一般由开发人员进行使用
	/*加载配置文件时就会把在配置文件对象进行创建*/
	
3ApplicationContext接口有实现类

3.Bean管理

1)什么是Bean管理
	1. Bean管理指的是两个操作
	2. Spring创建对象
	3. Spring注入属性
2)IOC操作Bean管理(基于xml)
1.基于xml方式创建对象
    <bean id="user" class="org.example.domain.User"></bean>
	<!--在Spring配置文件中,使用bean标签,标签里添加对应属性,就可以实现对象创建
		id属性:唯一标识(别名)
		class属性:全限定名称			
		name属性:与id类似,可加特殊符号,基本不用了
		
		创建对象时候,默认执行对象的无参构造方法
-->
2.基于xml方式注入属性
1、DI:依赖注入,就是注入属性
<!--	第一种注入方法:使用set注入-->
<!--set方法注入属性-->
<bean id="book" class="org.example.domain.Book">
<!--使用property完成属性注入
    name属性:指向类里面属性名称
    value属性:注入的值-->
	<property name="bname" value="易筋经"/>
	<property name="bauthor" value="达摩老祖"/>
</bean>
//测试代码块
@Test
public void testBook(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean01.xml");
    Book book = applicationContext.getBean("book",Book.class);    
    System.out.println(book);    
    book.testDome();
}
<!--第二种注入方法:使用有参构造注入 -->
<!--有参构造注入属性-->
<bean id="Book" class="org.example.domain.Book">
	<constructor-arg name="bname" value="abc"/>
	<constructor-arg name="bauthor" value="bcd"/>
</bean>
//测试方法
@Test
public void testBook2(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean01.xml");
        Book book = applicationContext.getBean("Book", Book.class);
        System.out.println(book);
        book.testDome();
}
2、P空间注入(了解)
 
<?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"<!--在xml中加入的标签-->
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="book" class="org.example.domain.Book" p:bname="qwe" p:bauthor="asd"/>
<!--测试方法类似,以后省略-->
3、注入属性-外部bean
    <!--1、service和dao对象的创建-->
    <bean id="userService" class="org.example.service.UserService">
        <!--注入userDao对象
            name属性值:类里面属性名称
            ref属性:创建userDao对象bean标签的id值
        -->
        <property name="userDao" ref="userDao"/>
    </bean>
    <bean id="userDao" class="org.example.dao.Impl.UserDaoImpl"/>
package org.example.service;

import org.example.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();
    }
}
public class UserDaoImpl implements UserDao {
	@Override
	public void update() {
		System.out.println("dao update....");
	}
}
//测试方法
public class TestSpring02 {
	@Test
	public void testBean02(){
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean02.xml");
		UserService userService = applicationContext.getBean("userService", UserService.class);
		System.out.println(userService);
		userService.add();
	}
}
4、注入属性-内部Bean级联赋值

​ 1)一对多关系:部门和员工

<!--注入属性-内部Bean-->
 <bean id="employ" class="org.example.domain.Employ">
 	<property name="name" value="lisi"/>
 	<property name="gender" value=""/>
 	<property name="department">
 	<bean class="org.example.domain.Department">
 		<property name="dName" value="实践部"/>
 	</bean>
 	</property>
 </bean>
public class Employ {
    private String name;
    private String gender;
    private Department department;
    public void setName(String name) {
			this.name = name;
		}
		public void setGender(String gender) {
			this.gender = gender;
		}    
		public void setDepartment(Department department) {
		  this.department = department;
		}
		public void add(){
			System.out.println(name+"::"+gender+"::"+department);
		}
}
public class Department {
	private String dName;
	public void setdName(String dName) {
		this.dName = dName;
		}
	@Override
	public String toString() {
		return "Department{" +                "dName='" + dName + '\'' +                '}';    
		}
}
5、注入属性-级联赋值

​ 1)第一种写法

<!--注入属性-级联赋值-->
<bean id="employ1" class="org.example.domain.Employ">
	<property name="name" value="lisi"/>
	<property name="gender" value=""/>
	<property name="department" ref="department"/>
</bean>
<bean id="department" class="org.example.domain.Department">
	<property name="dName" value="财政部"/>
</bean>

​ 2)第二种写法

<!--注入属性-级联赋值-->
<bean id="employ1" class="org.example.domain.Employ">
	<property name="name" value="lisi"/>
	<property name="gender" value=""/>
	<property name="department.dName" value="实践部"/>
	<!--需要在Employ类中对Department对象创建get方法-->
</bean>
public class Employ {
	private Department department;
	public Department getDepartment() {
		return department;
	}
}
3、基于xml方式注入其他类型属性
1、字面量

​ 1)null值

        <!--设置空值-->
        <property name="bEdit">
        		<null></null>
        </property>

​ 2)属性包含特殊符号

        <!--设置特殊符号			1、使用实体代替“<”			2、把带特殊符号内容写到CDATA中-->
        <property name="bEdit"><!--value="<<南京》》"-->
        		<value><![CDATA[<<南京>]]></value>
        </property>
2、注入集合属性

1)注入数组类型属性

2)注入List集合类型属性

3)注入Map集合类型属性

4)set集合类型属性

        <bean id="jihe" class="org.example.domain.Student">
            <!--1)注入数组类型属性-->
            <property name="arrs">
                <array>
                    <value>123</value>
                    <value>qwe</value>
                </array>
            </property>
            <!--2)注入List集合类型属性-->
            <property name="list">
                <list>
                    <value>456</value>
                    <value>asd</value>
                </list>
            </property>
            <!--3)注入Map集合类型属性-->
            <property name="map">
                <map>
                    <entry key="123" value="asd"/>
                    <entry key="456" value="qwe"/>
                </map>
            </property>
            <!--4)set集合类型属性-->
            <property name="set">
                <set>
                    <value>789</value>
                    <value>zxc</value>
                </set>
            </property>
             <!--注入集合对象类型值-->
            <property name="courseList">
                <list>
                    <ref bean="course1"/>
                    <ref bean="course2"/>

                </list>
            </property>
        </bean>
    	<bean id="course2" class="org.example.domain.Course">
      	  <property name="cName" value="lisi"/>
    	</bean>
    	<bean id="course1" class="org.example.domain.Course">
     	   <property name="cName" value="zhangsan"/>
   		</bean>
        </bean>
package org.example.domain;

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

public class Student {
//    1)注入数组类型属性
    private String[] arrs;
    public void setArrs(String[] arrs) {
        this.arrs = arrs;
    }
    //    2)注入List集合类型属性
    private List<String> list;
    public void setList(List<String> list) {
        this.list = list;
    }

//    3)注入Map集合类型属性

    private Map<String ,String > map;

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    //    4)set集合类型属性
    private Set<String> set;

    public void setSet(Set<String> set) {
        this.set = set;
    }
//    5)集合对象类型
    private List<Course> courseList;

    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }

    @Override
    public String toString() {
        return "Student{" +
                "arrs=" + Arrays.toString(arrs) +
                ", list=" + list +
                ", map=" + map +
                ", set=" + set +
                ", courseList=" + courseList +
                '}';
    }
} 


public class Course {
    private String cName;

    public void setcName(String cName) {
        this.cName = cName;
    }

    @Override
    public String toString() {
        return "Course{" +
                "cName='" + cName + '\'' +
                '}';
    }
}
4、IOC操作Bean管理(基于FactoryBean)
Spring有两种类型的bean:普通bean ,工厂bean(FactoryBean)

工厂Bean:在配置文件定义bean类型可以和返回类型不一样

1、创建类。让这个类作为FactoryBean,实现接口FactoryBean2、实现接口里面的方法,在实现的方法中定义返回的Bean类型 
<bean id="mybean" class="org.example.domain.MyBean"/>
public class MyBean implements FactoryBean<Course> {
	@Override
	public boolean isSingleton() {
		return FactoryBean.super.isSingleton();
	}
	@Override
	public Course getObject() throws Exception {
		Course course = new Course();
		course.setcName("abc");
		return course;
	}
	@Override
	public Class<?> getObjectType() {
		return null;
		}
	}
	public void test03(){
	    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean02.xml");
	    Course course = applicationContext.getBean("mybean",Course.class);
	    System.out.println(course);
	}
5、Bean作用域
1、在Spring里面,设置创建Bean实例是单实例还是多实例
2、在Spring里,默认情况下,Bean是单实例单实例:对象地址将会一样多实例:对象地址不一样,即是两个对象
3、设置单实例或者多实例<bean id="mybean" class="org.example.domain.MyBean" scope=""/>    scope属性:			
	1)singleton:默认值,标识单实例对象,加载Spring配置文件时,就会创建单实例对象            
	2)prototype:表示多实例对象,在调用getBean方法时候创建多实例对象
	3)request(了解):
	4)session(了解):
6、Bean生命周期

1、通过构造器创建Bean实例(无参构造)

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

3、调用Bean的初始化方法(需要进行配置初始化方法)

4、Bean可以使用了(对象获取到了)

5、当容器关闭时,调用Bean的销毁方法(需要进行配置销毁的方法)

<bean id="number" class="org.example.domain.Number" init-method="init" destroy-method="destroy">
    <property name="NName" value="abc"/>
</bean>
public class Number {
    public Number() {
        System.out.println("1、通过构造器创建Bean实例(无参构造)");
    }

    private String NName;

    public void setNName(String NName) {
        this.NName = NName;
        System.out.println("2、为Bean的属性设置值和对其他Bean引用(调用set方法");
    }

    public void init(){
        System.out.println("3、调用Bean的初始化方法(需要进行配置初始化方法)");
    }
    public void destroy(){
        System.out.println("5、当容器关闭时,调用Bean的销毁方法(需要进行配置销毁的方法)");
    }
}

    @Test
    public void test04(){
//ApplicationContext中没有close()方法,需要调用ApplicationContext的子接口ClassPathXmlApplicationContext
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean02.xml");
        Number number = context.getBean("number", Number.class);
        System.out.println(number);
        System.out.println("4、Bean可以使用了(对象获取到了)");
        context.close();
        System.out.println("5、当容器关闭时,调用Bean的销毁方法(需要进行配置销毁的方法)");
    }

**6、Bean后置处理器:**Bean生命周期有七步

​ 1、通过构造器创建Bean实例(无参构造)

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

3、把Bean实例传递Bean后置处理器的方法

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

5、把Bean实例传递Bean后置处理器的方法

​ 6、Bean可以使用了(对象获取到了)

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

<!--配置后置处理器
	效果:为当前.xml配置文件中的所有bean标签都配置后置处理器
-->
	<bean id="number02" class="org.example.domain.Number"/>
7、基于XML的自动装配(不常用)
 根据指定装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入
        <bean id="" class="" autowire=""/>
8、引入外部文件
1、直接配置数据库信息
	1)配置Driver连接池
	2)引入连接池Driver.jar包
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
     <property name="url" value="jdbc:mysql://localhost:3306/student"/>
     <property name="username" value="root"/>
     <property name="password" value="123456"/>
</bean>
2、引入外部属性文件配置数据库连接池
	1)创建外部属性文件,properties格式文件,写数据库信息
	2)把外部properties属性文件引入到spring配置文件中
		<!--引入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 http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClass}"/>
        <property name="url" value="${prop.url}"/>
        <property name="username" value="${prop.userName}"/>
        <property name="password" value="${prop.password}"/>
    </bean>
</beans>
properties属性文件:
prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/student
prop.userName=root
prop.password=123456
3)IOC操作Bean管理(基于注解方式)
Spring针对Bean管理中创建对象提供注解
	1、@Component
	2、@Service
	3、@Controller
	4、@Repository
上面四个注解功能是一样的,都可以用来创建Bean实例
1、基于注解方式实现对象创建

1)引入依赖aop.jar包

spring-aop-5.3.9.jar

2)开启组件扫描

<!--添加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 http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--
        开启组件扫描
            1、如果扫描多个包,多个包使用逗号隔开
            2、扫描包上层目录
    -->
<context:component-scan base-package="org.example.domain"/>
</beans>

3)创建类,在类上面加注解

//在注解里面value属性值可以省略不写
//默认值是类名称,首字母小写
@Component(value = "student")
//<bean id = "student" class="..."/>
public class Student {
    public void add(){
        System.out.println("add......");
    }
}
@Test
public void test01(){
	ApplicationContext context = new ClassPathXmlApplicationContext("bean01.xml");
	Student student = context.getBean("student", Student.class);
	System.out.println(student);
	student.add();
}

4)开启组件扫描细节配置

    <context:component-scan base-package="org.example" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.XXX"/>
    <!--use-default-filters="false" 
    <context:include-filter type="annotation" expression="org.springframework.stereotype.XXX"/>
    只扫描带注解XXX-->    
    </context:component-scan>
    <context:component-scan base-package="org.example">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.XXX"/>
    <!--
    <context:include-filter type="annotation" expression="org.springframework.stereotype.XXX"/>
    不扫描带注解XXX
    -->
    </context:component-scan>
2、基于注解方式实现属性注入
  1. @Autowired:根据属性类型进行自动装配

    ​ 1)把service和dao对象创建,在service和dao类添加创建注解

    ​ 2)在service里面注入dao对象,在service类添加dao类型属性,在属性上面使用注解

     //dao类
    	@Repository
    	public class UserDaoImpl implements UserDao{
     	 @Override
     	 public void add() {
            System.out.println("dao add....");
     	}
    

}


```java
   //service类
   @Service
   public class UserService {
       //定义dao类型属性
       //不需要添加set方法
       //添加注入属性注解
       @Autowired//根据类型进行注入
       private UserDao userDao;
       public void add(){
               System.out.println("service add.......");
               userDao.add();
       }
}
<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">

    <context:component-scan base-package="org.example"/>
</beans>
  1. @Qualifier:根据属性名称进行注入

    ​ 1)@Qualifier注解的使用,要和@Autowired一起使用

    @Service
    public class UserService {
        //定义dao类型属性
        //不需要添加set方法
        //添加注入属性注解
        @Autowired//根据类型进行注入
        @Qualifier(value = "userDaoImpl01")//根据属性名称进行注入
        private UserDao userDao;
        public void add(){
            System.out.println("service add.......");
            userDao.add();
        }
    }
    
  2. @Resource:可以根据类型注入,也可以根据名称注入

@Service
public class UserService {
    //定义dao类型属性
    //不需要添加set方法
    //添加注入属性注解
    //    @Autowired
    //根据类型进行注入
    //    @Qualifier(value = "userDaoImpl01")
    //根据属性名称进行注入
    //    @Resource//根据类型进行注入
    @Resource(name = "userDaoImpl01")
    private UserDao userDao;
    public void add(){
    		System.out.println("service add.......");
    		userDao.add();
    }
}
  1. @Value:根据普通类型属性
@Value("abc")private String name;
3、完全注解开发(主要用于SpringBoot)

1)创建配置类,替代xml配置文件

@Configuration
//作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"org.example"})
//等同于xml中的<context:component-scan base-package="org.example"/>
public class SpringConfig {}

2)创建测试类

    @Test    public void test03(){        //加载配置类        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);        UserService userService = applicationContext.getBean("userService", UserService.class);        System.out.println(userService);        userService.add();    }

4)AOP

概念:	1、面向切面编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。    2、不通过修改源代码方式,在主干功能里添加新功能

1、底层原理

1)使用动态代理

​ 1.有接口情况,使用JDK动态代理

​ 创建接口实现类代理对象,增强类的方法

​ 2.没有接口情况,使用CGLIB动态代理

​ 创建当前类子类的代理对象

2、AOP(JDK动态代理)

1)使用JDK动态代理,使用Proxy类里面的方法创建代理对象

newProxyInstance(CalssLoader loader,<?>[] interface, InvocationHandler h)    第一个参数:类加载器    第二个参数:增强方法所在的类,这个类实现的接口,支持多个接口    第三个参数:实现这个接口InvocationHandler,创建代理对象,写增强的方法

实现:

//1、创建接口,定义方法public interface UserDao {    public int add(int a , int b);    public String update(String id);}
//2、创建接口实现类,实现方法
public class UserDaoImpl implements UserDao {
    @Override
    public int add(int a, int b) {
        return a+b;
    }
    @Override
    public String update(String id) {
        return id;
    }
}

//3、使用Proxy类创建接口代理对象
package org.example.service;

import org.example.dao.UserDao;
import org.example.dao.impl.UserDaoImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class JDKProxy {
    public static void main(String[] args) {
        Class[] interfaces = {UserDao.class};
//        Proxy.newProxyInstance(JDKProxy.class.getClassLoader(),interfaces, new InvocationHandler() {
//            @Override
//            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
//                return null;
//            }
//        });
        UserDaoImpl userDaoImpl = new UserDaoImpl();
        UserDao userDao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDaoImpl));
        int res = userDao.add(1,2);
        System.out.println("result="+res);
    }
}
//创建代理对象
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、术语

1)连接点:类里面哪些方法可以被增强,这些方法称为连接点

2)切入点:实际被增强的方法

3)通知(增强):

1. 实际增强的逻辑部分称为通知2. 通知有多种类型  	1. 前置通知  	2. 后置通知:(@After)方法之后通知,(@AfterReturning)方法返回值之后通知  	3. 环绕通知  	4. 异常通知  	5. 最终通知:finally

4)切面:是动作,把通知应用到接入点的过程

4、AOC操作

1)准备

1、Spring框架一般都是基于AspectJ实现AOP操作

​ AspectJ不是Spring组成部分,独立AOP框架,一般把AspectJ和Spring框架一起使用,进行AOP操作

2、基于AspectJ实现AOP操作

​ 1、基于xml配置文件实现

​ 2、基于注解方式实现(使用)

3、在项目工程里面引入

4、切入点表达式

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

​ 2)语法结构:

execution([][][][][][][权限修饰符] [返回类型] [类全路径].[方法名称] ([参数列表]))

举例一:对org.example.dao.UserDao类里面的add进行增强

execution(* org.example.dao.UserDao.add(..))

举例二:对org.example.dao.UserDao类里面的所有方法进行增强

execution(* org.example.dao.UserDao.*(..))

举例三:对org.example.dao包里面所有类,类里面的所有方法进行增强

execution(* org.example.dao.*.*(..))
2)AOP操作:基于AspectJ配置文件

1、创建两个类,增强类和被增强类,创建方法

public class Book {    public void buy(){        System.out.println("buy what?");    }}public class BookProxy {    public void befory(){        System.out.println("hello");    }}

2、在Spring配置文件中创建两个类对象

   <!--在Spring配置文件中创建两个类对象-->    <bean id="book" class="org.example.aopxml.Book"/>    <bean id="bookproxy" class="org.example.aopxml.BookProxy"/>

3、在Spring配置文件中配置切入点

<!--创建aop属性空间--><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">    <!--在Spring配置文件中创建两个类对象-->    <bean id="book" class="org.example.aopxml.Book"/>    <bean id="bookproxy" class="org.example.aopxml.BookProxy"/>    <!--配置aop增强-->    <aop:config>        <!--切入点-->        <aop:pointcut id="p" expression="execution(* org.example.aopxml.Book.buy(..))"/>        <!--配置切面-->        <aop:aspect ref="bookproxy">            <!--增强作用在具体的方法上-->            <aop:before method="befory" pointcut-ref="p"        </aop:aspect>    </aop:config><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">    <!--在Spring配置文件中创建两个类对象-->    <bean id="book" class="org.example.aopxml.Book"/>    <bean id="bookproxy" class="org.example.aopxml.BookProxy"/>    <!--配置aop增强-->    <aop:config>        <!--切入点-->        <aop:pointcut id="p" expression="execution(* org.example.aopxml.Book.buy(..))"/>        <!--配置切面-->        <aop:aspect ref="bookproxy">            <!--增强作用在具体的方法上-->            <aop:before method="befory" pointcut-ref="p"        </aop:aspect>    </aop:config></beans>

​ 4、测试

    @Test    public void testXml(){        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean01.xml");        Book book = applicationContext.getBean("book01", Book.class);        book.buy();    }
3)AOP操作:基于AspectJ注解

1、创建类,在类中定义方法

public class User {    public void add(){        System.out.println("add...");    }}

2、创建增强类(编写增强逻辑)

​ 1)在增强类中,创建方法,让不同方法代表不同通知类型

public class UserProxy {//    前置通知    public void before(){        System.out.println("before....");    }}

3、进行通知的配置

​ 1)在Spring配置文件中,开启注解扫描

<?xml version="1.0" encoding="UTF-8"?><!--创建名称空间aop和context--><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 http://www.springframework.org/schema/context/spring-context.xsd                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">    <!--开启注解扫描-->    <context:component-scan base-package="org.example.aopanno"/></beans>

​ 2)使用注解创建User和UserProxy对象

@Component
public class User {
    public void add(){
        System.out.println("add...");
    }
}


@Component
@Aspect
public class UserProxy {

//    前置通知
    //前置注解表示作为前置通知
    @Before(value = "execution(* org.example.aopanno.User.add(..))")
    public void before(){
        System.out.println("before....");
    }
}

​ 3)在增强类上面添加注解@Aspect

@Component
@Aspect
public class UserProxy {

//    前置通知
    //前置注解表示作为前置通知
    @Before(value = "execution(* org.example.aopanno.User.add(..))")
    public void before(){
        System.out.println("before....");
    }
}

​ 4)在Spring配置文件中开启生成代理对象

​ 1、在增强类中,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

@Component@Aspectpublic class UserProxy {//    前置通知    //前置注解表示作为前置通知    @Before(value = "execution(* org.example.aopanno.User.add(..))")    public void before(){        System.out.println("before....");    }}

5、测试

    @Test    public void testAnno(){        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean02.xml");        User user = applicationContext.getBean("user", User.class);        user.add();    }

6、相同的切入点抽取

    @Pointcut(value = "execution(* org.example.aopanno.User.add(..))")    public void pointDemo(){            }//    前置通知    //前置注解表示作为前置通知    @Before(value = "pointDemo()")    public void before(){        System.out.println("before....");    }

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

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

@Component@Aspect@Order(1)public class UserProxy {

8、完全使用注解开发

​ 1)创建配置类,不需要创建xml文件

@Configuration@ComponentScan(basePackages = "org.example")@EnableAspectJAutoProxy(proxyTargetClass = true)public class ConfigAop {

5)JDBCTemplate

1、概念

1)Spring框架对JDBC进行封装,使用JDBCTemplate方便实现对数据库操作

2、准备工作

1)引入相关jar包

2)在Spring配置文件配置数据库连接池

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">     <property name="driverClassName" value="com.mysql.jdbc.Driver"/>     <property name="url" value="jdbc:mysql://localhost:3306/student"/>     <property name="username" value="root"/>     <property name="password" value="123456"/></bean>

3)配置JDBCTemplate对象,注入DataSource

    <!--JDBCTemplate对象-->    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <!--注入DataSource-->        <property name="dataSource" ref="dataSource"/>    </bean>

4)创建service类,dao类,在dao注入JDBCTemplate对象

<?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 http://www.springframework.org/schema/context/spring-context.xsd                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">    <!--开启组件扫描-->    <context:component-scan base-package="org.example"/>    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>        <property name="username" value="root"/>        <property name="password" value="123456"/>    </bean>    <!--JDBCTemplate对象-->    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">        <!--注入DataSource-->        <property name="dataSource" ref="dataSource"/>    </bean></beans>
@Servicepublic class BookService {    //注入dao    @Autowired    private BookDao bookDao;}@Repositorypublic class BookDaoImpl implements BookDao {    //注入JDBCTemplate    @Autowired    private JdbcTemplate jdbcTemplate;}

3、JDBCTemplate操作数据库(添加)

1)对应数据库创建实体类

public class User {
    private int id;
    private String name;
    private String pasw;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getPasw() {
        return pasw;
    }

    public void setPasw(String pasw) {
        this.pasw = pasw;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pasw='" + pasw + '\'' +
                '}';
    }
}

2)编写service和dao

​ 1、在dao进行数据库添加操作

@Servicepublic class BookService {    //注入dao    @Autowired    private BookDao bookDao;    //添加的方法    public void addBook(Book book){        bookDao.add(book);    }}@Repositorypublic class BookDaoImpl implements BookDao {    //注入JDBCTemplate    @Autowired    private JdbcTemplate jdbcTemplate;//    添加的方法    @Override    public void add(Book book) {//        创建sql语句        String sql= "insert into book value (?,?,?)";//        调用方法实现        Object[] objects = {book.getId(),book.getName(),book.getPasw()};        int update = jdbcTemplate.update(sql, objects);        System.out.println(update);    }}

​ 2、调用JDBCTemplate对象里面update方法实现添加操作

​ 有两个参数:

​ 1)sql语句

​ 2)可变参数,设置sql语句

@Repositorypublic class BookDaoImpl implements BookDao {    //注入JDBCTemplate    @Autowired    private JdbcTemplate jdbcTemplate;//    添加的方法    @Override    public void add(Book book) {//        创建sql语句        String sql= "insert into book value (?,?,?)";//        调用方法实现        Object[] objects = {book.getId(),book.getName(),book.getPasw()};        int update = jdbcTemplate.update(sql, objects);//增删改都是用update()方法        System.out.println(update);    }}

​ 3、测试

    @Test    public void testJDBKTemplate(){        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean01.xml");        BookService bookService = applicationContext.getBean("bookService",BookService.class);        Book book = new Book();        book.setId(1);        book.setName("Java");        book.setPasw("web");        bookService.addBook(book);    }

4、JDBCTemplate操作数据库(查询)

1)返回某个值

1、查询表里面有多少条记录,返回是某个值

2、使用JDBCTemplate实现查询返回某个值代码

    @Override    public int selectCount() {        String sql = "select count(*) from book";        Integer integer = jdbcTemplate.queryForObject(sql, Integer.class);        //queryForObject()两个参数            //1)sql语句            //2)返回类型Class        return integer;    }
2)返回对象
    @Override
    public Object selectObject(int id) {
        String sql = "select * from book where id=?";
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
        /**queryForObject()
         * 三个参数:
         *          1)sql语句
         *          2)RowMapper,是接口,
         *              返回不同类型数据,使用这个接口里面的实现类完成数据封装
         *          3)sql语句值
         */
        return book;
    }
3)返回集合
    @Override
    public List<Book> selectList() {
        String sql = "select * from book";
        List<Book> books = (List<Book>) jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        /**query()
         * 三个参数:
         *          1)sql语句
         *          2)RowMapper,是接口,
         *              返回不同类型数据,使用这个接口里面的实现类完成数据封装
         *          3)sql语句值
         */
        return books;
    }

5、DBCTemplate批量操作(增删改相似,以增加操作为例)

    @Override
    public void batchAddBook(List<Object[]> bookList) {
        String sql = "insert into book value (?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, bookList);
        /**
         * batchUpdate()
         * 两个参数:
         *          1、sql语句
         *          2、List集合,多条添加记录
         */
        System.out.println(Arrays.toString(ints));
    }
    @Test
    public void testSelectBatchAdd(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean01.xml");
        BookService bookService = applicationContext.getBean("bookService", BookService.class);
        List<Object[]> objects = new ArrayList<>();
        Object[] o1 = {5,"qwe","fsad"};
        Object[] o2 = {6,"qwe","fsad"};
        Object[] o3 = {7,"qwe","fsad"};
        Object[] o4 = {8,"qwe","fsad"};
        objects.add(o1);
        objects.add(o2);
        objects.add(o3);
        objects.add(o4);
        bookService.batchAdd(objects);
    }

6)事务

概念:事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败,所有操作都失败
特性(ACID):
	1、原子性
	2、一致性
	3、隔离性
	4、持久性

1、事务操作(搭建事务操作环境)

1、创建数据库表,添加记录

2、创建service,搭建dao,完成对象创建和注入关系

​ 1)service注入,在dao注入JDBCTemplate,在JDBCTemplate注入DataSource

​ 2)在dao创建两个方法,多钱和少钱的方法,在service中创建转账方法

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


    <!--开启组件扫描-->
    <context:component-scan base-package="org.example"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--JDBCTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入DataSource-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>
@Service
public class UserService {
    //注入dao
    @Autowired
    private UserDao userDao;
    //转账方法
    public void accountMoney(){
        //lucy少100
        userDao.reduceMoney();
        //mary多100
        userDao.addMoney();
    }
}

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //lucy转给mary
    @Override
    public void addMoney() {
        String sql = "update account set money = money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    }

    @Override
    public void reduceMoney() {
        String sql = "update account set money = money-? where username=?";
        jdbcTemplate.update(sql,100,"lucy");
    }
}

    @Test
    public void testAccountMoney(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean01.xml");
        UserService userService = applicationContext.getBean("userService", UserService.class);
        userService.accountMoney();
    }

2、出现异常

@Service
public class UserService {
    //注入dao
    @Autowired
    private UserDao userDao;
    //转账方法
    public void accountMoney(){
        try {
            //第一步 开启事务
            //第二步 进行业务操作
            //lucy少100
            userDao.reduceMoney();
            //模拟异常
            int i = 10/0;
            //mary多100
            userDao.addMoney();
            //第三步 没有异常发生,提交事务
        }catch (Exception e){
            //第四步 出现异常,事务回滚
        }

    }
}

3、事务操作(Spring事务管理介绍)

1、事务添加到JaxaEE三层结构里面Service层(业务逻辑层)

2、在Spring进行事务管理操作

​ (1)有两种方式:

​ 编程式事务管理

​ 声明式事务管理(常用)

3、声明式事务管理

​ 1)基于注解方式

​ 2)基于xml配置文件方式

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

5、Spring事务管理API

​ 1)提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类

PlatformTransactionManager接口
	DataSourceTransactionManager实现类

4、事务操作(注解声明式事务管理)

1、在Spring:配置文件中配置事务管理器

2、在Spring配置文件,开启事务注解

​ 1)在Spring配置文件中引入名称空间tx

​ 2)开启事务注解

​ 3)在service类上面(获取service类里面方法上面)添加事务注解

	1. @Transactional//可以添加类上面,也可以添加到方法上面
	2. 如果这个注解添加类上面,这个类里面所有方法都添加事务
	3. 如果这个注解添加方法上面,这个类里面这个方法都添加事务
<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"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">


    <!--开启组件扫描-->
    <context:component-scan base-package="org.example"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--JDBCTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入DataSource-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--创建事务管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
</beans>
@Service
@Transactional//可以加载类上面,也可以添加到方法上面
public class UserService {
    //注入dao
    @Autowired
    private UserDao userDao;
    //转账方法
    public void accountMoney(){
            //第一步 开启事务
            //第二步 进行业务操作
            //lucy少100
            userDao.reduceMoney();
            //模拟异常
            int i = 10/0;
            //mary多100
            userDao.addMoney();
            //第三步 没有异常发生,提交事务
            //第四步 出现异常,事务回滚
    }
}
1)事务操作(声明式事务管理参数配置)

1)在service类上面添加注解@Transactional,在这个注解里面可以配置事务相关此参数

@Transactional(
propagation = Propagation.REQUIRED,//(默认)
/*事务传播行为:
  1)多事务方法(对数据库表数据进行变化的操作)直接进行调用,这个过程
    REQUIRED:
    	如果add方法本身有事务,调用update方法之后,update使用当前add方法里面事务
    	如果add方法本身没有事务,调用update方法之后,创建新事务
    REQUIRED _NEW
		使用add方法调用update方法,如果add无论是否有事务,都创建新的事务
*/
isolation = Isolation.REPEATABLE_READ,//(默认
/*事务隔离级别
	1)事务有特性成为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题。
    2)有三个读问题:脏读、不可重复读、虚(幻)读
    3)脏读:一个未提交事务读取到另一个未提交事务的数据
	4)不可重复读:一个未提交事务读取到另一提交事务修改数据
	5)虚读:一个未提交事务读取到另一提交事务添加数据
	6)通过设置事务隔离性,解决读问题

*/
timeout = 5,
/*超时时间
	1)事务需要在一定时间内进行提交,如果不提交进行回滚
	2) 默认值是-1,不超时,设置时间以秒单位进行计算
*/
readOnly = true,
/*是否只读
	1) 读:查询操作,写:添加修改删除操作
	2) readOnly,默认值 false,表示可以查询,可以添加修改删除操作
	3) 设置readOnly值是true,设置成true之后,只能查询
*/
rollbackFor = ,
/*回滚
	1)设置查询哪些异常进行事务回滚v
*/
noRollbackFor = )
/*不回滚
	1) 设置出现哪些异常不进行事务回滚s
*/

5、事务操作(完全注解声明式事务管理)

1、创建配置类,使用配置类代替xml配置文件

@Configuration//配置类
@ComponentScan(basePackages = "org.example")//组件扫描
@EnableTransactionManagement//开启事务
public class TxConfig {
    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        return druidDataSource;
    }

//    创建jdbcTemplate对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
//        到IOC容器中根据类型找到dataSource
        JdbcTemplate jdbcTemplate =new JdbcTemplate();
//        注入dataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
//    创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}

6、事务操作(XML声明式事务管理)

1)配置事务管理器

2)配置通知

3)配置切入点和切面

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


    <!--开启组件扫描-->
    <context:component-scan base-package="org.example"/>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--JDBCTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入DataSource-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--1、创建事务管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--2、配置通知-->
    <tx:advice id ="txadvice">
        <!--配置事务参数-->
        <tx:attributes>
            <!--指定那种规则上面添加事务-->
            <tx:method name="accountMoney" propagation="REQUIRED"/><!--可以使用方法名-->
            <!--<tx:method name="account*"/>&lt;!&ndash;以account开头的&ndash;&gt;-->
        </tx:attributes>
    </tx:advice>
    
    <!--3、配置切入点和切面-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="pt" expression="execution(* org.example.service.UserService.*(..))"/>
        <!--配置切面-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
    </aop:config>
</beans>

7)Spring5新

1、整个Spring5框架的代码基于Java8,运行时兼容JDK9,许多不建议使用的类和方法在代码库中删除
2、Spring 5.o框架自带了通用的日志封装。
	(1) Spring5已经移除Log4jConfigListener,官方建议使用Log4j2
	(2) Spring5框架整合Log4j2
		第一步引入jar包。
		log4j-api-2.11.2.jar
		log4j-core-2.11.2jar
		log4j-slf4j-impl-2.11.2.jar
		slf4j-api-1.7.30.jar
		第二步创建log4j2.xml
<?xml version="1.o"encoding="UTF-8"?>
<!--日志级别以及优先级排序:0FF 〉FATAL 〉ERROR > WARN>INFO〉DEBUG〉TRACE > ALL-->
<!--Configuration后面的status用于设置log4i2自身内部的信息输出,可以不设置,当设置成trace时,可以看到log4.j2内部各种详细输出-->
<configuration status=" INFO">
    <!--先定义所有的appender-->
    <appenders>
    <!--输出日志信息到控制台-->T
        <console name="Console" target="SYSTEM_OUT">
        <!--控制日志输出的格式-->
            <PatternLayout pattern="%d{yyyy-M-dd HH:mm:ss. SSS}[%t] %-5level %logger f36} - %msg%n"/>
        </console>
    </appenders>
    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
    <!--root:用于指定项目的根日志,如果没有单独指定Logger,则会使用root作为默认的日志输出-->
    <loggers>
        <root level=" info">
            <appender-ref ref="Console"/>
        </root>
    </ loggers>
</ configuration>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值