Spring_00000

Spring介绍

官网地址:https://spring.io/
下载地址:https://repo.spring.io/release/org/springframework/spring/

Spring框架是一个开放源代码的J2EE应用程序框架,由Rod Johnson发起,是针对bean的生命周期进行管理的轻量级容器(lightweight container)。Spring框架主要由七部分组成,分别是 Spring Core、Spring AOP、Spring ORM、Spring DAO、Spring Context、Spring Web和Spring Web MVC。

Spring是一个轻量级框架。
Spring是非侵入式的:典型地,Spring应用中的对象不依赖于Spring的特定类。
控制反转——Spring通过一种称作控制反转(IoC)的技术促进了低耦合。
它的底层设计模式采用了工厂模式,所有的 Bean 都需要注册到Bean工厂中,将其初始化和生命周期的监控交由工厂实现管理。

下载

下载Spring请按如下步骤进行。
1、登录站点,下载Spring的最新稳定版本。
下载的压缩包:spring-5.2.6.RELEASE-dist.zip,解压后的文件夹(spring-framework-5.2.6.RELEASE)目录介绍:
docs:该文件下包含Spring的相关文档,包括API参考文档、开发手册。
libs:该文件夹下存放Spring各个模块的jar文件,每个模块均提供开发所需的jar文件、以“-javadoc”后缀表示的API和以“-sources”后缀表示的源文件三项内容。
schema:配置Spring的某些功能时需要用到的schema文件,对于已经继承了Spring的IDE环境(如MyEclipse),这些文件不需要专门引入。

Maven搭建Spring项目

创建Maven项目,添加如下依赖。

	<dependencies>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>5.3.21</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>5.3.21</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>5.3.21</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>5.3.21</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.3.21</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>5.3.21</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>5.3.21</version>
		</dependency>
		
	    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>5.3.21</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>5.3.21</version>
			<scope>test</scope>
		</dependency>
		
		<!-- 以下不是Spring的jar -->
		<!-- MySQL数据库驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.29</version>
		</dependency>
		
		<!-- druid数据库连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.2.11</version>
		</dependency>
		
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.18.0</version>
		</dependency>
				
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.18.0</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>2.0.0-alpha7</version>
		</dependency>
		
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>2.18.0</version>
			<scope>test</scope>
		</dependency>
		
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>com.springsource.org.aspectj.weaver</artifactId>
			<version>1.6.4.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.aopalliance</groupId>
			<artifactId>com.springsource.org.aopalliance</artifactId>
			<version>1.0.0</version>
		</dependency>

		<dependency>
			<groupId>net.sourceforge.cglib</groupId>
			<artifactId>com.springsource.net.sf.cglib</artifactId>
			<version>2.2.0</version>
		</dependency>
		
	</dependencies>

控制反转(Inversion of Control,IoC)也称为依赖注入(Dependency Injection,DI),是面向对象编程中的一种设计理念,用来降低程序代码之间的耦合度。

IOC底层原理:工厂模式:
在这里插入图片描述
1、IoC思想基于IoC容器完成,IOC容器底层就是对象工厂。
2、Spring提供的IOC容器的两种实现方式:(两个接口)
(1)BeanFactory:IOC容器基本实现,是Spring内部的使用接口,不提供开发人员使用。
加载配置文件时不会创建对象,在获取对象(使用)时才去创建对象。
(2)ApplicationContext:BeanFactory接口的子接口,提供了更多更强大的功能,一般由开发人员进行使用。
加载配置文件时就会把在配置文件中的对象进行创建。

eclipse中快捷键F4或Ctrl+T弹出如下图类的继承图:
在这里插入图片描述
什么是bean管理?
bean管理指的是两个操作:
1、Spring创建对象
2、Spirng注入属性

bean管理的操作有两种方式:
1、基于xml配置文件方式实现
2、基于注解方式实现

创建bean,User.java

package com.jack.spring.spring_demo.bean;

public class User {

    public void add() {

        System.out.println("add");

    }

}

创建xml文件,配置具体bean

<!--配置Bean;name属性和id属性一样,区别是name属性值可以使用特殊字符-->
    <bean id="user" class="com.jack.spring.spring_demo.bean.User" />

1、在 spring 配置文件中,使用 bean 标签,标签里面添加对应属性,就可以实现对象的创建。
2、在 bean 标签有很多属性,介绍常用的属性
id 属性:唯一标识
class 属性:类全路径
3、创建对象的时候,默认也是执行无参构造方法完成对象的创建。

	@Test
    public void testUser() {
        /*
         * Spring提供实现供IOC容器的两种方式:(两个接口)
         * 1、BeanFactory:IOC 容器基本实现,是 Spring 内部的使用接口,不提供开发人员使用
         * 加载配置文件的时候不会创建对象,在获取对象(使用)时才去创建对象
         * 2、ApplicationContext:BeanFactory 接口的子接口,提供更多更强大的功能,一般由开发人员进行使用,
         * 加载配置文件的时候就会把配置文件中的对象进行创建
         */

        //加载spring配置文件
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\spring_demo\\xml\\user1.xml");
        //获取bean对象
        User user = applicationContext.getBean("user", User.class);

        System.out.println(user);
        
        user.add();
        
        applicationContext.close();

    }

创建日志文件log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
        <!--日志级别以及优先级排序: OFF>FATAL>ERROR>warn>INFO>DEBUG>TRACE>ALL-->
        <!--Configuration后面的status用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,可以看到log4j2内部各种详细输出-->
<configuration status="info">

    <!--先定义所有的appender-->
    <appenders>
        <!--输出日志信息到控制台-->
        <console name="Console" target="SYSTEM_OUT">
            <!--控制日志输出的格式-->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36}-%msg%n"/>
        </console>
    </appenders>

    <!--然后定义logger,只有定义logger并引入appender,appender才会生效-->
    <!--root:用于指定项目的根日志,如果没有单独指定Logger,则会使用root作为默认的日志输出-->
    <loggers>
        <root level="info">
            <appender-ref ref= "Console"/>
        </root>
    </loggers>

</configuration>

基于xml配置文件方式操作bean

DI(依赖注入),就是注入属性。

setter方法注入

public void setName(String name) {
	this.name = name;
}
User user = new User();
user.setName("宋江");

1、创建类,定义属性和对应的 set 方法

/**
* 演示使用 set 方法进行注入属性
*/
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、在 spring 配置文件中配置对象创建,配置属性注入。

<!--2 set 方法注入属性-->
< bean  id= "book"  class= "com.jack.spring.Book">
	<!--使用 property 完成属性注入
	name:类里面属性名称
	value:向属性注入的值
	-->
	< property  name= "bname"  value="水浒传"/>
	< property  name= "bauthor"  value="施耐庵"/>
</ bean>

有参构造方法注入

1、创建类,定义属性,创建属性对应有参数构造方法。

/**
* 使用有参数构造注入
*/
public class Orders {

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

2、在 spring 配置文件中进行配置

<!--3 有参数构造注入属性-->
< bean  id= "orders"  class= "com.jack.spring.Orders">
	< constructor-arg  name= "oname"  value="电脑"/>
	< constructor-arg  name= "address"  value= "China"/>
</ bean>
User user = new User(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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置bean;name属性和id属性一样,区别是name属性值可以使用特殊字符-->
    <bean id="user" class="com.jack.spring.spring_demo.bean.User" />


    <!--
        如何设置单实例还是多实例
    1、在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例
    2、scope属性值
     (1)默认值,singleton,表示是单实例对象
     (2)prototype,表示是多实例对象

    singleton和prototype的区别
    1、singleton:单实例,prototype:多实例
    2、设置scope值是singleton时,加载spring配置文件时就会创建单实例对象
        设置scope值是prototype时,不是在加载spring配置文件时创建对象,在调用getBean方法时创建多实例对象
    -->
    <!--set方法注入属性-->
    <bean id="book" class="com.jack.spring.spring_demo.bean.Book" scope="prototype"> <!--prototype ['prəʊtətaɪp] n.原型;范例;雏形-->

        <!--使用property完成属性注入-->
        <property name="name" value="三国演义" />
        <property name="author" value="罗贯中" />

        <!--给属性赋值null-->
        <!-- 
        <property name="address" >
            <null/>
        </property>
        -->

        <!--属性值中包括特殊字符
           方式一:把<>进行转义;&lt &gt
           方式二:把带特殊符号内容写到CDATA中
        -->
        <property name="address" >  
            <value><![CDATA[<<南京>>]]></value>
        </property>
    </bean>

    <!--默认是无参构造方法注入;使用constructor-arg标签使用有参构造方法注入-->
    <bean id="order" class="com.jack.spring.spring_demo.bean.Order">
        <constructor-arg name="name" value="computer" />
        <constructor-arg name="address" value="China" />

        <!--
        <constructor-arg index="0" value="computer"/>
          也可以使用index通过索引注入
        -->
    </bean>

    <!--
    p名称标签
    xmlns:p="http://www.springframework.org/schema/p"

    <bean id="book" class="com.jack.spring.Book"
          p:name="施耐庵"
          p:author="水浒传" />
    -->

</beans>
package com.jack.spring.spring_demo.bean;

import lombok.AllArgsConstructor;

import lombok.NoArgsConstructor;

//@Data //set方法注入
@AllArgsConstructor //有参构造方法注入
@NoArgsConstructor
public class Book {

    private String name;
    private String author;
    private String address;

    public void testDemo(){

        System.out.println(name + "\n" + author + "\n" + address);

    }

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

    public void setAuthor(String author) {
        this.author = author;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public String getAuthor() {
        return author;
    }

    public String getAddress() {
        return address;
    }

}
	@Test
    public void testBook(){
    	
        //加载spring配置文件
    	AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\spring_demo\\xml\\user1.xml");

        //获取bean对象
        Book book = applicationContext.getBean("book", Book.class);
        Book book1 = applicationContext.getBean("book", Book.class);

        System.out.println(book.hashCode());
        System.out.println(book1.hashCode());

        System.out.println(book);
        System.out.println(book1);

        book.testDemo();
        
        applicationContext.close();

    }

p名称空间注入

使用p名称空间注入属性,可以简化基于xml配置方式。

第一步:在配置文件中添加p名称空间。

<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

第二步:进行属性注入。

<bean id="user2" class="com.jack.spring.spring_demo.bean.User" p:id="2" p:username="卢俊义" p:password="lujunyi" />

特殊处理

1 、字面量
(1)属性值为null

<property  name= "password">
	<null/>
</property>

(2)属性值包含特殊符号
1、把<>进行转义 &lt; &gt;
2、把带特殊符号的内容写到CDATA。

<property  name= "address">
	<value>
		<![CDATA[<<南京>>]]>
	</value>
</property>

MVC模式:用spring创建对象、注入属性

创建User实体类User.java

package com.jack.spring.spring_demo.bean;

public class User {
	
	private int id;
	private String username;
	private String password; 
	
	public User() {}
	
	public User(int id, String username, String password) {
		
		this.id = id;
		this.username = username;
		this.password = password;
	}



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


	public void setUsername(String username) {
		this.username = username;
	}


	public void setPassword(String password) {
		this.password = password;
	}

	public void showInformation() {
		System.out.println(id + "\t" + username + "\t" + password);
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}
	
}

创建接口UserDao.java

package com.jack.spring.spring_demo.dao;

public interface UserDao {
    void update();
}

创建接口UserDao的实现类UserDaoImpl.java

package com.jack.spring.spring_demo.dao;

public class UserDaoImpl implements UserDao{

    @Override
    public void update() {
        System.out.println("接口UserDao的实现类UserDaoImpl里的update方法!");
    }

}

创建UserService.java

package com.jack.spring.spring_demo.service;

import com.jack.spring.spring_demo.dao.UserDao;

public class UserService {

    //UserDao类型属性
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void add() {

        System.out.println("UserService类里的add方法!");

        //创建UserDao对象;原始方式
        //UserDao userDao = new UserDaoImpl();
        userDao.update();
        
    }

}

创建配置文件

<?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">

    <!--service和dao对象创建-->
    <bean id="userService" class="com.jack.spring.spring_demo.service.UserService">
        <!--注入userDao对象
            name属性:类里面的属性名称
            ref属性:创建userDao对象bean标签的id值
        -->
        <property name="userDao" ref="userDaoImpl1" />
    </bean>

    <bean id="userDaoImpl1" class="com.jack.spring.spring_demo.dao.UserDaoImpl"/>

</beans>

test

@Test
    public void testUser1() {
    	
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/jack/spring/spring_demo/xml/user.xml");
        UserService userService = applicationContext.getBean("userService", UserService.class);

        userService.add();
        
        applicationContext.close();
        
    }

print

UserService类里的add方法!
接口UserDao的实现类UserDaoImpl里的update方法!

Spring创建对象;注入属性;内部bean

一对多

属性注入、赋值

1、一对多关系:部门和员工
一个部门有多个员工,一个员工属于一个部门
部门是一,员工是多
2、在实体类之间表示一对多关系,员工表示所属部门,使用对象类型属性进行表示

创建bean
Department.java

package com.jack.spring.spring_demo.bean;

public class Department {

    private String departmentName;
    
    public void setDepartmentName(String departmentName) {
    	this.departmentName = departmentName;
    } 
    
    public void departmentShowInformation() {
    	System.out.println("类Department中的departmentShowInformation方法" + ": departmentName="+ departmentName);
    }

	@Override
	public String toString() {
		return "Department [departmentName=" + departmentName + "]";
	}
	
}

Employee.java

package com.jack.spring.spring_demo.bean;

public class Employee {

    private String employeeName;
    private String gender;
    
    private Department department; //员工属于某一个部门;使用对象的形式表示

    public void setEmployeeName(String employeeName) {
		this.employeeName = employeeName;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}
	
    public void setDepartment(Department department) {
		this.department = department;
	}

	public void employeeShowInformation() {
        
		//System.out.println(employeeName + "\t" + gender + "\t" + department.getDepartmentName());
        System.out.println(employeeName + "\t" + gender + "\t" + department);
    }

}

employee.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 -->
    <bean id="employee" class="com.jack.spring.spring_demo.bean.Employee">

        <property name="employeeName" value="宋江" />
        <property name="gender" value="" />

		<!-- 设置对象类型属性 -->
        <property name="department">
            <bean class="com.jack.spring.spring_demo.bean.Department">
                <property name="departmentName" value="保安部"/>
            </bean>
        </property>

    </bean>

</beans>

test

	@Test
    public void testEmployee() {
    	
        AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("com/jack/spring/spring_demo/xml/employee.xml");
        
        Employee employee = abstractApplicationContext.getBean("employee", Employee.class);
        
        abstractApplicationContext.close();
        
        employee.employeeShowInformation();
             
    }
级联赋值
写法一
<?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="employee" class="com.jack.spring.spring_demo.bean.Employee">

        <property name="employeeName" value="卢俊义" />
        <property name="gender" value="" />

    		<!--<property name="dept">
            <bean class="com.jack.spring.spring_demo.bean.Department" >
                <property name="departmentName" value="保安部"/>
            </bean>
        </property>-->

        <property name="department" ref="department"/>

    </bean>

    <bean id="department" class="com.jack.spring.spring_demo.bean.Department">
        <property name="departmentName" value="财务部" />
    </bean>

</beans>

test

	@Test
    public void testEmployee1() {
    	
    	AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("com/jack/spring/spring_demo/xml/employee1.xml");
        Employee employee = abstractApplicationContext.getBean("employee", Employee.class);

        abstractApplicationContext.close();
        
        employee.employeeShowInformation();
        
    }

print

卢俊义	男	Department [departmentName=财务部]
写法二

在Employee.java中添加department的get方法

public Department getDepartment() {
		return department;
	}

创建employee2.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="employee" class="com.jack.spring.spring_demo.bean.Employee">

        <property name="employeeName" value="吴用" />
        <property name="gender" value="" />

        	<!--<property name="dept"  >
            <bean class="com.jack.spring.bean.Department" >
                <property name="departName" value="保安部"/>
            </bean>
        </property>-->

        <property name="department" ref="department"/>
        <property name="department.departmentName" value="技术部" />

    </bean>

	<bean id="department" class="com.jack.spring.spring_demo.bean.Department">
		 <!-- <property name="departmentName" value="财务部" /> -->
	</bean>
   
</beans>

test

	@Test
    public void testEmployee2() {
    	
    	AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("com/jack/spring/spring_demo/xml/employee2.xml");
        Employee employee = abstractApplicationContext.getBean("employee", Employee.class);

        abstractApplicationContext.close();
        
        employee.employeeShowInformation();
        
    }

print

吴用	男	Department [departmentName=技术部]

注入集合类型属性

创建实体类Student.java

package com.jack.spring.collection.bean;

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

import com.jack.spring.factory_bean.bean.Course;

public class Student {

    //数组类型属性
    private String[] courses;
    //List集合类型属性
    private List<String> list;
    //Set集合类型属性
    private Set<String> set;
    //map集合类型属性
    private Map<String, String> map;

    //学生所学的多门课程
    private List<Course> listCourse;

    public void setCourses(String[] courses) {
		this.courses = courses;
	}

	public void setList(List<String> list) {
		this.list = list;
	}

	public void setSet(Set<String> set) {
		this.set = set;
	}

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

	public void setListCourse(List<Course> listCourse) {
		this.listCourse = listCourse;
	}

    public void print() {
    	
        System.out.println(Arrays.toString(courses));
        System.out.println(list);
        System.out.println(set);
        System.out.println(map);
        System.out.println(listCourse);
        
    }

}

创建实体类Course.java

package com.jack.spring.collection.bean;

//课程类
public class Course {

    private String courseName; //课程名称

	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

	@Override
	public String toString() {
		return "Course [courseName=" + courseName + "]";
	}

}

创建配置文件student.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>
注入数组类型属性
    <bean id="student" class="com.jack.spring.collection.bean.Student">

        <!-- 数组类型属性注入 -->
        <property name="courses">
            <array>
                <value>Java</value>
                <value>MySQL</value>
                <value>oracle</value>
            </array>
            
            <!-- 数组类型注入属性也可以使用list标签 -->
            <!-- <list>
                <value>Java</value>
                <value>MySQL</value>
                <value>oracle</value>
            </list> -->
            
        </property>
    
    </bean>

test

	@Test
    public void testStudent() {
        
    	AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\collection\\xml\\student.xml");
        Student student = abstractApplicationContext.getBean("student", Student.class);
        abstractApplicationContext.close();
        
        student.print();
        
    }
注入List集合类型属性
    <bean id="student" class="com.jack.spring.collection.bean.Student">
    <!--list类型属性注入-->
        <property name="list">
            <list>
                <value>宋江</value>
                <value>李逵</value>
                <value>吴用</value>
            </list>
        </property>
    </bean>
注入Set集合类型属性
	<bean id="student" class="com.jack.spring.collection.bean.Student">
		<!--set类型属性注入-->
	        <property name="set" >
	            <set>
	                <value>MySQL</value>
	                <value>Redis</value>
	                <value>Java</value>
	            </set>
	        </property>
	</bean>
注入Map集合类型属性
	<bean id="student" class="com.jack.spring.collection.bean.Student">
		<!--map类型属性注入-->
	        <property name="map">
	            <map>
	                <entry key="JavaKey" value="JavaValue"/>
	                <entry key="redisKey" value="redisValue"/>
	                <entry key="oracleKey" value="oracleValue"/>
	            </map>
	        </property>
	</bean>

在集合里面设置对象类型值

	<bean id="student" class="com.jack.spring.collection.bean.Student">
		<!--注入List类型属性,但是集合中的value是对象-->
	        <property name="listCourse">
	            <list>
	                <ref bean="course" />
	                <ref bean="course1" />
	                <ref bean="course2" />
	            </list>
	        </property>
	</bean>

	<!--创建course对象-->
    <bean id="course" class="com.jack.spring.collection.bean.Course">
        <property name="courseName" value="Java" />
    </bean>
    <bean id="course1" class="com.jack.spring.collection.bean.Course">
        <property name="courseName" value="maria" />
    </bean>
    <bean id="course2" class="com.jack.spring.collection.bean.Course">
        <property name="courseName" value="MyBatis" />
    </bean>

完整的xml文件(student.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="student" class="com.jack.spring.collection.bean.Student">

        <!-- 数组类型属性注入 -->
        <property name="courses">
            <array>
                <value>Java</value>
                <value>MySQL</value>
                <value>oracle</value>
            </array>
            
            <!-- 数组类型注入属性也可以使用list标签 -->
            <!-- <list>
                <value>Java</value>
                <value>MySQL</value>
                <value>oracle</value>
            </list> -->
            
        </property>

        <!--list类型属性注入-->
        <property name="list">
            <list>
                <value>宋江</value>
                <value>李逵</value>
                <value>吴用</value>
            </list>
        </property>

        <!--set类型属性注入-->
        <property name="set" >
            <set>
                <value>MySQL</value>
                <value>Redis</value>
                <value>Java</value>
            </set>
        </property>

        <!--map类型属性注入-->
        <property name="map">
            <map>
                <entry key="JavaKey" value="JavaValue"/>
                <entry key="redisKey" value="redisValue"/>
                <entry key="oracleKey" value="oracleValue"/>
            </map>
        </property>

        <!--注入List类型属性,但是集合中的value是对象-->
        <property name="listCourse">
            <list>
                <ref bean="course" />
                <ref bean="course1" />
                <ref bean="course2" />
            </list>
        </property>

    </bean>

    <!--创建course对象-->
    <bean id="course" class="com.jack.spring.collection.bean.Course">
        <property name="courseName" value="Java" />
    </bean>
    <bean id="course1" class="com.jack.spring.collection.bean.Course">
        <property name="courseName" value="maria" />
    </bean>
    <bean id="course2" class="com.jack.spring.collection.bean.Course">
        <property name="courseName" value="MyBatis" />
    </bean>
    
</beans>

提取List类型属性注入

在spring配置文件中引入名称空间util。
beans标签添加属性:
xmlns:util=“http://www.springframework.org/schema/util”
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd

创建student1.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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!--提取List类型属性注入-->
    <util:list id="studentList">
        <value>宋江</value>
        <value>卢俊义</value>
        <value>吴用</value>
    </util:list>

	<bean id="student" class="com.jack.spring.collection.bean.Student">
		<property name="list" ref="studentList"/>
	</bean>
	
</beans>

test

	@Test
    public void testStudent1() {
    	
    	AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\collection\\xml\\student1.xml");
        Student student = abstractApplicationContext.getBean("student", Student.class);
        abstractApplicationContext.close();
        
        student.print();
        
    }

IoC操作FactoryBean

Spring有两种类型bean,一种普通bean,另外一种工厂bean(FactoryBean )。

普通bean:在配置文件中定义bean类型就是返回类型。

工厂bean:在配置文件定义bean类型可以和返回类型不一样。
第一步:创建类,让这个类作为工厂bean,实现接口FactoryBean。
第二步:实现接口里面的方法,在实现的方法中定义返回的bean类型。

创建Course.java

package com.jack.spring.factory_bean.bean;

//课程
public class Course {

    private String courseName; //课程名称

	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

	@Override
	public String toString() {
		return "Course [courseName=" + courseName + "]";
	}

}

创建类MyBean.java,让这个类作为工厂bean,实现接口FactoryBean。

package com.jack.spring.factory_bean.bean;

import org.springframework.beans.factory.FactoryBean;

public class MyBean implements FactoryBean<Course> {

    @Override
    public Course getObject() {

        Course course = new Course();
        course.setCourseName("java");
        
        return course;

    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

}

创建配置文件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">

    <bean id="myBean" class="com.jack.spring.factory_bean.bean.MyBean"/>

</beans>

test

@Test
    public void testBean(){
        
    	AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\factory_bean\\xml\\bean.xml");
        Course course = abstractApplicationContext.getBean("myBean", Course.class);
        abstractApplicationContext.close();
        
        System.out.println(course);
        
    }

bean的作用域

在Spring里,默认bean是单实例对象。

如何设置单实例与多实例?
1、在spring配置文件bean标签里有属性(scope)用于设置单实例还是多实例。
2、scope属性值
第一个值:默认值,singleton,表示是单实例对象。
第二个值:prototype,表示是多实例对象。

singleton和prototype的区别?
1、singleton单实例,prototype多实例。
2、设置scope值是singleton时,加载spring配置文件时就会创建单实例对象。
设置scope值是prototype时,不是在加载spring配置文件的时候创建对象,而是在调用getBean方法时创建多实例对象。

	<!--set方法注入属性-->
    <bean id="book" class="com.jack.spring.spring_demo.bean.Book" scope="singleton"> <!--prototype ['prəʊtətaɪp] n.原型;范例;雏形-->

        <!--使用property完成属性注入-->
        <property name="name" value="三国演义" />
        <property name="author" value="罗贯中" />

        <!--给属性赋值null-->
        <!-- 
        <property name="address" >
            <null/>
        </property>
        -->

        <!--属性值中包括特殊字符
           方式一:把<>进行转义;&lt &gt
           方式二:把带特殊符号内容写到CDATA中
        -->
        <property name="address" >  
            <value><![CDATA[<<南京>>]]></value>
        </property>
    </bean>
	@Test
    public void testBook(){
    	
        //加载spring配置文件
    	AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\spring_demo\\xml\\user1.xml");

        //获取bean对象
        Book book = applicationContext.getBean("book", Book.class);
        Book book1 = applicationContext.getBean("book", Book.class);

        System.out.println(book.hashCode());
        System.out.println(book1.hashCode());

        System.out.println(book);
        System.out.println(book1);

        book.testDemo();
        
        applicationContext.close();

    }

print:

22069592
22069592
com.jack.spring.spring_demo.bean.Book@150c158
com.jack.spring.spring_demo.bean.Book@150c158
三国演义
罗贯中
<<南京>>

当设置scope="singleton"时,输出结果:

22069592
1160003871
com.jack.spring.spring_demo.bean.Book@150c158
com.jack.spring.spring_demo.bean.Book@4524411f
三国演义
罗贯中
<<南京>>

bean的生命周期

1、生命周期:从对象创建到对象销毁的过程。
2、bean的生命周期,共有五步:
(1)通过无参数构造方法创建bean实例。
(2)调用set方法为bean实例的属性设置值和对其他bean引用。
(3)调用bean的初始化的方法(需要进行配置初始化的方法)。
(4)使用bean对象(对象获取到了)。
(5)当容器关闭的时候,调用bean的销毁方法(需要进行配置销毁的方法)

bean的后置处理器,bean生命周期有七步:
(1)通过无参数构造方法创建bean实例。
(2)调用set方法为bean实例的属性设置值和对其他bean引用。
(3)把bean实例传递bean后置处理器的方法postProcessBeforeInitialization
(4)调用bean的初始化的方法(需要进行配置初始化的方法)。
(5)把bean实例传递bean后置处理器的方法postProcessAfterInitialization
(6)使用bean对象(对象获取到了)。
(7)当容器关闭的时候,调用bean的销毁方法(需要进行配置销毁的方法)

创建User.java

package com.jack.spring.bean_lifecycle.bean;

public class User {

    private String userName;

    //无参数构造器
    public User(){
        System.out.println("bean生命周期:第一步:执行无参数构造方法创建bean实例");
    }

    public void setUserName(String userName){
        this.userName = userName;
        System.out.println("bean生命周期:第二步:调用set()设置属性值");
    }

    //创建执行的初始化的方法
    public void initializeMethod() {
        System.out.println("bean生命周期:第三步:执行初始化方法");
    }

    //创建执行的销毁的方法
    public void destroyMethod() {
        System.out.println("bean的生命周期:第五步:执行销毁方法");
    }

	@Override
	public String toString() {
		return "User [name=" + userName + "]";
	}

}

创建MyBeanPostProcessor.java
类MyBeanPostProcessor实现BeanPostProcessor接口

package com.jack.spring.bean_lifecycle.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

//后置处理器
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

        System.out.println("在初始化执行之前执行的方法");

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化执行之后执行的方法");
        return bean;
    }

}

创建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">

    <bean id="user" class="com.jack.spring.bean_lifecycle.bean.User" init-method="initializeMethod" destroy-method="destroyMethod">
        <property name="userName" value="phone"/>
    </bean>

    <!--配置后置处理器-->
    <bean id="myBeanPostProcessor" class="com.jack.spring.bean_lifecycle.bean.MyBeanPostProcessor"/>

</beans>

test

	@Test
    public void testBeanLifeCycle(){

        //加载spring配置文件
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\bean_lifecycle\\xml\\bean.xml");

        //获取bean对象
        User user = classPathXmlApplicationContext.getBean("user", User.class);

        System.out.println("bean生命周期:第四步:获取bean创建的实例对象:" + user);

        //手动销毁bean实例
        classPathXmlApplicationContext.close();

    }

自动装配

自动装配:根据指定的装配规则(属性名称或属性类型),Spring自动将匹配的属性值进行注入

创建Department.java

package com.jack.spring.automated_assembly.bean;

public class Department {
	
}

创建Employee.java

package com.jack.spring.automated_assembly.bean;

public class Employee {

    private Department department;
   
    public void setDepartment(Department department) {
		this.department = department;
	}

	public void testMethod(){
    	
        System.out.println(department);
        
    }

	@Override
	public String toString() {
		return "Employee [department=" + department + "]";
	}
	
}

创建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">

	<!-- setter手动注入 -->
	<bean id="employee" class="com.jack.spring.automated_assembly.bean.Employee">
        <property name="department" ref="department"/>
    </bean>
    

    <!--配置自动装配
    bean标签属性:autowire
    
    autowire属性常用值:
    	byName:根据属性名称注入,注入值的bean的id值和类属性名称一样
    	byType:根据属性类型注入
    -->
    
    <bean id="department" class="com.jack.spring.automated_assembly.bean.Department"/>
    
    <bean id="employee1" class="com.jack.spring.automated_assembly.bean.Employee" autowire="byType">
        <!-- <property name="department" ref="department"/> -->
    </bean>

    <bean id="employee2" class="com.jack.spring.automated_assembly.bean.Employee" autowire="byName">
        <!-- <property name="department" ref="department"/> -->
    </bean>
	
</beans>

test

package com.jack.spring.automated_assembly.text;

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

import com.jack.spring.automated_assembly.bean.Employee;

public class TestAutomatedAssembly {

    @Test
    public void testAutomatedAssembly() {
    	
    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\automated_assembly\\xml\\bean.xml");
        Employee employee = classPathXmlApplicationContext.getBean("employee2", Employee.class);
        classPathXmlApplicationContext.close();
        
        System.out.println(employee);
        
    }

}

引入外部属性文件配置数据库连接池

配置Druid(德鲁伊)数据库连接池

引入Druid数据库连接池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/test_jack"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>-->

引入外部属性文件配置数据库连接池

创建外部属性文件jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test_jack
jdbc.username=root
jdbc.password=root

引入context名称空间
xmlns:context=“http://www.springframework.org/schema/context”
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

创建druid.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">

    <!--直接配置连接池
    <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/test_jack"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>-->

    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置连接池-->
    <bean id="dataSource3" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

</beans>

基于注解方式操作bean

Spring 针对Bean管理中创建对象提供的注解:
1、@Component
2、@Service
3、@Controller
4、@Repository

上面四个注解的功能是一样的,都可以用来创建bean实例。

组件扫描方式

创建bean.xml配置文件:
添加:
xmlns:context=“http://www.springframework.org/schema/context”
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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="com.jack.spring.annotation_bean"/>

</bean>

创建接口UserDao

package com.jack.spring.annotation_bean.dao;

public interface UserDao {
	
    void add();
    
}

创建类UserDaoImpl,实现UserDao接口。

package com.jack.spring.annotation_bean.dao;

import org.springframework.stereotype.Service;

@Service(value = "userDaoImpl")
public class UserDaoImpl implements UserDao {

    @Override
    public void add() {
    	
        System.out.println("类UserDaoImpl实现的UserDao中的add方法");
        
    }
    
}

创建类UserService

package com.jack.spring.annotation_bean.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.jack.spring.annotation_bean.dao.UserDao;

import javax.annotation.Resource;

//@Component(value="userService") //相当于spring配置文件中的<bean id="userService" class="com.jack.spring.annotation_bean.service.UserService"/>
@Service
//@Controller
//@Repository
public class UserService {

//    @Autowired //根据类型注入
//    @Qualifier(value = "userDaoImpl1") //根据名称注入,要和@Autowired一起使用
//    private UserDao userDao;

    //@Resource //根据类型注入
    //private UserDao userDao;

    @Resource(name = "userDaoImpl") //根据名称注入
    private UserDao userDao;

    @Value(value = "这是类UserService里属性username的值")
    private String username;

    public void add() {
    	
        System.out.println("类UserService的add方法" + "======" + username);
        
        userDao.add();
        
    }

}

test

	@Test
    public void testAnnotation(){
        
    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\annotation_bean\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        classPathXmlApplicationContext.close();
        
        System.out.println(userService);
        
        userService.add();
        
    }

完全注解方式

创建类SpringConfig

package com.jack.spring.annotation_bean.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration //作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.jack.spring.annotation_bean"})
public class SpringConfig {

}

test

	@Test
    public void testSpringConfig(){
    	
    	AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = annotationConfigApplicationContext.getBean("userService", UserService.class);
        annotationConfigApplicationContext.close();
        
        System.out.println(userService);
        
        userService.add();
        
    }

基于注解方式进行属性注入

1、@Autowired:根据属性类型进行自动装配
第一步:创建service和dao对象,在service和dao实现类UserDaoImpl上添加创建对象注解。
第二步:在service中注入dao对象,在service类中添加dao类型属性,在属性上面使用注解@Service

@Service
public class UserService {

	//定义 dao 类型属性
	//不需要添加 set 方法
	//添加注入属性注解
	@Autowired
	private  UserDao  userDao; ;
	public void add() {
	
	System. out .println( "service add.......");
	
		userDao.add();
		
	}
	
}

2、@Qualifier:根据名称进行注入。
@Qualifier注解和上面@Autowired 一起使用。

//定义dao类型属性
//不需要添加set方法
//添加注入属性注解
@Autowired //根据类型进行注入
@Qualifier(value =  "userDaoImpl1")  //根据名称进行注入
private UserDao  userDao;

3、@Resource:可以根据类型注入,可以根据名称注入

//@Resource //根据类型进行注入
@Resource(name =  "userDaoImpl1") //根据名称进行注入
private UserDao  userDao;

4、@Value:注入普通类型属性

@Value(value =  "abc")
private String  name;

AOP

AOP(Aspect Oriented Programming,面向切面编程)是一种设计思想,是软件设计领域中的面向切面编程,它是OOP(Object Oriented Programming,面向对象编程)的一种补充和完善。它以通过预编译方式和运行期动态代理方式,实现在不修改源代码的情况下给程序动态统一添加额外功能的一种技术。

oriented ['ɔːrɪəntɪd] adj.以…为方向的;以…为目的的

什么是AOP?
面向切面(方面)编程,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高开发的效率。
在这里插入图片描述

底层原理

AOP底层使用动态代理,有两种方式:
1、使用JDK动态代理
创建接口实现类代理对象,增强类的方法。
2、使用CGLIB动态代理
创建子类的代理对象,增强类的方法。
在这里插入图片描述

使用JDK动态代理

使用Proxy类里面的方法创建代理对象。

java.lang.reflect Class Proxy
public class Proxy extends Object implements Serializable

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用处理程序。

参数
  loader - 类加载器来定义代理类
  interfaces - 代理类实现的接口列表;增强方法所在的类,这个类实现的接口,支持多个接口。
  h - 调度方法调用的调用处理函数;实现这个接口InvocationHandler,创建代理对象,写增强的部分。
                    
结果:具有由指定的类加载器定义并实现指定接口的代理类的指定调用处理程序的代理实例

创建接口

package com.jack.spring.aop.proxy.dao;

public interface UserDao {
    int add(int number, int numberOther);
    String update(String id);
}

创建接口实现类

package com.jack.spring.aop.proxy.dao;

public class UserDaoImpl implements UserDao {

    @Override
    public int add(int number, int numberOther) {

        //System.out.println("a");

        System.out.println("类UserDaoImpl里的add(int number, int numberOther)方法执行了");

        //System.out.println("b");

        return number + numberOther;
        
    }

    @Override
    public String update(String id) {
    	
        System.out.println("类UserDaoImpl里的update(String id)方法执行了");
        
        return id;
        
    }

}

创建代理对象

package com.jack.spring.aop.proxy.invocation_handler;

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

public class MyInvocationHandler implements InvocationHandler {

    private final Object object;

    public MyInvocationHandler(Object object) {
    	
        System.out.println("构造方法被调用!");
        this.object = object;
        
    }

    private int count = 0;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        ++count ;

        System.out.println("增强的业务,方法执行前!");

        System.out.println(method.getName());
        System.out.println(Arrays.toString(args)); //传递的参数

        Object resultObject = method.invoke(object, args); //被增强的方法

        System.out.println("增强的业务,方法执行后!");

        System.out.println("count:" + count);

        System.out.println(object);

        return resultObject;
        
    }

}

使用Proxy类创建接口代理对象

package com.jack.spring.aop.proxy.jdk_proxy;

import java.lang.reflect.Proxy;

import com.jack.spring.aop.proxy.dao.UserDao;
import com.jack.spring.aop.proxy.dao.UserDaoImpl;
import com.jack.spring.aop.proxy.invocation_handler.MyInvocationHandler;

/**
 * @author Jack
 * @see com.jack.spring.aop.proxy.jdk_proxy
 * @since JDK1.8
 */
//JDK动态代理
public class JDKProxy {

    public static void main(String[] args) {

        /*
        public static Object newProxyInstance(ClassLoader loader,
                                            Class<?>[] interfaces,
                                            InvocationHandler h)
                                            throws IllegalArgumentException
                                            
               返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用处理程序。


                    参数
                    loader - 类加载器来定义代理类
                    interfaces - 代理类实现的接口列表
                    h - 调度方法调用的调用处理函数
                    结果
                    具有由指定的类加载器定义并实现指定接口的代理类的指定调用处理程序的代理实例
         */

        //创建接口实现类的代理对象
        Class<?>[] interfaces = {UserDao.class};

        /*Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        });*/

        UserDao userDao = new UserDaoImpl();

        UserDao userDao1 = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new MyInvocationHandler(userDao));

        int result = userDao1.add(1, 2);

        System.out.println("result:" + result);

    }

}

创建接口

package com.jack.spring.proxy.demo_001.dao;

public interface Target {
	
	int sum(int number, int otherNumber);
	
	String getName(String name);
	
}

创建接口实现类

package com.jack.spring.proxy.demo_001.dao;

public class TargetImpl implements Target{

	@Override
	public int sum(int number, int otherNumber) {
		
		System.out.println("两个数的和是:");
		return number + otherNumber;
		
	}

	@Override
	public String getName(String name) {
		
		return name;
		
	}

}

创建通知代码

package com.jack.spring.proxy.demo_001.advice;

public class Advice {

	public void before() {
		System.out.println("前置方法执行!");
	}	
	
	public void after() {
		
		System.out.println("后置方法执行!");
	}
	
}

test

package com.jack.spring.proxy.demo_001.text;

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

import org.junit.Test;

import com.jack.spring.proxy.demo_001.advice.Advice;
import com.jack.spring.proxy.demo_001.dao.Target;
import com.jack.spring.proxy.demo_001.dao.TargetImpl;

public class TestProxy {
	
	@Test
	public void testTarget() {
		
		TargetImpl targetImpl = new TargetImpl();
		Advice advice = new Advice();
		
		Target target = (Target)Proxy.newProxyInstance(
								
								targetImpl.getClass().getClassLoader(),
				                targetImpl.getClass().getInterfaces(),
				                new InvocationHandler() {
			
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				
				System.out.println("参数:" + Arrays.asList(args));
				System.out.println("方法名称" + method.getName());
				
				advice.before();
				Object object = method.invoke(targetImpl, args);
				advice.after();
				
				System.out.println("参数:" + Arrays.asList(args));
				System.out.println("方法名称" + method.getName());
				
				return object;
				
			}
			
		});
		
		int sum = target.sum(1, 2);
		System.out.println(sum);
		
		System.out.println("================");
		
		String name = target.getName("宋江");
		System.out.println(name);
		
	}

}

AOP术语

1、连接点:类里面哪些方法可以被增强,这些方法称为连接点。
2、Pointcut(切入点):实际被真正增强的方法,称为切入点。目标对象中,已经被增强的方法。调用这几个方法之前、之后或者抛出异常时干点什么,那么就用切入点来定义这几个方法。
3、Advice(通知/增强):实际增强的逻辑部分称为通知(增强)。增强方法的代码、想要的功能。
4、Target(目标对象):被代理对象,被通知的对象,被增强的类对象。
5、Weaving(织入):将通知应用到连接点形成切入点的过程。
6、Proxy(代理):将通知织入到目标对象之后形成的代理对象。
7、aspect(切面):切入点+通知。通知(Advice)说明了干什么的内容(即方法体代码)和什么时候干(什么时候通过方法名中的before,after,around等就能知道),二切入点说明了在哪干。

通知的类型:
前置通知
后置通知
环绕通知
异常通知
最终通知

4、切面:把通知应用到切入点的过程。
在这里插入图片描述

AOP操作

Spring框架一般都是基于AspectJ 实现AOP。

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

AspectJ是一个面向切面的框架,它扩展了Java语言。AspectJ定义了AOP语法,它有一个专门的编译器用来生成遵守Java字节编码规范的Class文件。

基于AspectJ实现AOP操作的两种方式:
1、基于xml配置文件实现。
2、基于注解方式实现。

在项目工程里面引入 AOP的相关依赖
在这里插入图片描述

切入点表达式

切入点表达式作用:指定对哪个类里面的哪个方法进行增强。
语法结构:

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

举例1:对com.company.dao.UserDao类里面的add方法进行增强。

execution(* com.company.dao.UserDao.add(..))

举例2:对 com.company.dao.UserDao类里面的所有的方法进行增强。

execution(* com.company.dao.UserDao.*(..))

举例3:对com.company.dao包里所有类,类里面所有方法进行增强。

execution(* com.company.dao.*.*(..))

AOP操作

AspectJ注解

1、创建类,在类里面定义方法。
User.java

2、创建增强类(编写增强逻辑)。
在增强类里面,创建方法,让不同方法代表不同通知类型。

3、(1)进行通知的配置:在 spring 配置文件中,开启注解扫描。
(2)使用注解创建 User 和 UserProxy 对象
(3)在增强类上面添加注解@Aspect

4、配置不同类型的通知:在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置。
5、相同的切入点抽取

	//相同切入点抽取
    @Pointcut(value = "execution(* com.jack.spring.aop.proxy_annotation.User.add(..))")
    public void point(){

    }

6、有多个增强类对同一个方法进行增强,可以设置增强类的优先级。
在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高。

package com.jack.spring.aop.proxy_annotation;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

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

    //前置通知
    @Before(value = "execution(* com.jack.spring.aop.proxy_annotation.User.add(..))")
    public void before() {
        System.out.println("UserProxy1:前置通知:@Before");
    }

}

创建类,在类里面定义方法。

package com.jack.spring.aop.proxy_annotation;

import org.springframework.stereotype.Component;

//被增强的类
@Component
public class User {
	
    public void add() {
    	
        //int i = 1/0; //演示异常通知
        System.out.println("add");
        
    }
    
}

创建增强类(编写增强逻辑)。
在增强类里面,创建方法,让不同方法代表不同通知类型。

package com.jack.spring.aop.proxy_annotation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

//增强类
@Component //创建对象
@Aspect //表示生成代理对象
@Order(3)
public class UserProxy {

    //相同切入点抽取
    @Pointcut(value = "execution(* com.jack.spring.aop.proxy_annotation.User.add(..))")
    public void point(){

    }

    //前置通知
    @Before(value = "point()")
    public void before() {
        System.out.println("前置通知:@Before");
    }

    //后置通知(返回通知)
    @AfterReturning(value = "point()")
    public void afterReturning() {
        System.out.println("后置通知:@AfterReturning");
    }

    //异常通知
    @AfterThrowing(value = "point()")
    public void afterThrowing() {
        System.out.println("异常通知:@AfterThrowing");
    }

    //最终通知
    @After(value = "point()")
    public void after() {
        System.out.println("最终通知:@After");
    }

    //环绕通知
    @Around(value = "point()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        System.out.println("环绕通知之前:@Around");

        //被增强的方法执行
        proceedingJoinPoint.proceed();

        System.out.println("环绕通知之后:@Around");

        return null;

    }

}

配置文件:开启注解扫描。

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

    <!--开启注解扫描-->
    <contetxt:component-scan base-package="com.jack.spring.aop.proxy_annotation"/>

    <!--开启Aspect生成代理对象-->
    <aop:aspectj-autoproxy/>

</beans>

test

package com.jack.spring.aop.proxy_annotation.text;

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

import com.jack.spring.aop.proxy_annotation.User;

public class TextProxyAnnotation {

    @Test
    public void testAOP() {
    	
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\aop\\proxy_annotation\\xml\\bean.xml");
        User user = classPathXmlApplicationContext.getBean("user", User.class);
        classPathXmlApplicationContext.close();
        
        user.add();
        
    }

}

完全使用注解开发:
创建配置类,不需要创建xml配置文件

@Configuration
@ComponentScan(basePackages = { "com.jack.spring.aop.proxy_annotation"})
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class ConfigAop {
}
AOP操作(AspectJ配置文件)

1、创建两个类,增强类和被增强类,创建方法。
2、在Spring配置文件中创建两个类对象

<!--创建对象-->
<bean id= "user" class="com.jack.spring.aop.proxy_annotation.User"></bean>
<bean id= "userProxy" class="com.jack.spring.aop.proxy_annotation.UserProxy"></bean>

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

<!--配置AOP增强-->
<aop:config>

	<!--切入点-->
	<aop:pointcut id="p" expression="execution(* com.jack.spring.aop.proxy_annotation.User.add(..))"/>
	
	<!--配置切面-->
	<aop:aspect ref="UserProxy">
		<!--增强作用在具体的方法上-->
		<aop:before method="before" pointcut-ref="p"/>
	</aop:aspect>

</aop:config>
package com.jack.spring.aop.proxy_xml;

import org.springframework.stereotype.Component;

@Component
public class Book {
    public void buy() {
        System.out.println("buy");
    }
}
package com.jack.spring.aop.proxy_xml;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Order(1)
public class BookProxy {
    public void before(){
        System.out.println("before");
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--创建对象-->
    <bean id="book2" class= "com.jack.spring.aop.proxy_xml.Book"/>
    <bean id="bookProxy" class= "com.jack.spring.aop.proxy_xml.BookProxy"/>

    <!--配置aop增强-->
    <aop:config>

        <!--切入点-->
        <aop:pointcut id= "p" expression= "execution(* com.jack.spring.aop.proxy_xml.Book.buy(..))"/>

        <!--配置切面-->
        <aop:aspect ref="bookProxy">

            <!--增强作用在具体的方法上-->
            <aop:before method="before" pointcut-ref="p"/>

        </aop:aspect>

    </aop:config>

</beans>
package com.jack.spring.aop.proxy_xml.text;

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

import com.jack.spring.aop.proxy_xml.Book;

public class TextProxyXML {

    @Test
    public void testProxyXML(){

    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\aop\\proxy_xml\\xml\\bean.xml");
        Book book = classPathXmlApplicationContext.getBean("book2", Book.class);
        classPathXmlApplicationContext.close();
        
        book.buy();

    }
}

JdbcTemplate

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

引入相关jar包
在这里插入图片描述
创建jdbc.properties外部属性文件。

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test_jack
jdbc.username=root
jdbc.password=root

在Spring配置文件中引入jdbc.properties外部属性文件并配置数据库连接池。

	<!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
	<!--配置数据库连接池-->
    <!-- DruidDataSource dataSource = new DruidDataSource(); -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <!--dataSource.setDriverClassName("com.mysql.jdbc.Driver"); 
			set方法注入
		-->
        <property name="driverClassName" value="${jdbc.driverClass}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

配置JdbcTemplate对象,注入DataSource。

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

开启组件扫描。

<!--开启组件扫描;使用注解方法进行注入-->
    <context:component-scan base-package="com.jack.spring.jdbc_template"/>

完整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"
       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"/>
    
    <!--配置数据库连接池-->
    <!-- DruidDataSource dataSource = new DruidDataSource(); -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <!--dataSource.setDriverClassName("com.mysql.jdbc.Driver"); 
			set方法注入
		-->
        <property name="driverClassName" value="${jdbc.driverClass}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

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

    <!--开启组件扫描;使用注解方法进行注入-->
    <context:component-scan base-package="com.jack.spring.jdbc_template"/>

</beans>

创建实体类User.java

package com.jack.spring.jdbc_template.entity;

import java.io.Serializable;

public class User implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String email;
       
	public User() {
		super();
	}

	public User(String username, String password, Integer age, String email) {
		super();
		this.username = username;
		this.password = password;
		this.age = age;
		this.email = email;
	}

	public User(Integer id, String username, String password, Integer age, String email) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
		this.age = age;
		this.email = email;
	}
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + ", email=" + email + "]";
	}
      
}

创建UserDao.java

public interface UserDao {

}

创建UserDaoImpl.java,添加注解,注入JdbcTemplate。

@Repository
public class UserDaoImpl implements UserDao{

    //@Autowired
    @Resource
    private JdbcTemplate jdbcTemplate;

}

创建UserService.java,添加注解,注入UserDao。

@Service
public class UserService {

    //注入dao
    //@Autowired
    //@Qualifier(value = "BookDaoImpl")
    @Resource
    private UserDao bookDao;

}

基本操作

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

添加操作

int org.springframework.jdbc.core.JdbcTemplate.update(String sql, @Nullable Object... args) throws DataAccessException

UserDao.java

	//add
    int addUser(User user);

UserDaoImpl.java

	@Override
    public int addUser(User user) {
    	
        //调用JdbcTemplate中的update()可以对数据库表进行add,update,delete操作
        //第一个参数:sql语句;第二个参数:可变参数,设置 sql 语句值
        String sql = "insert into t_user values (null, ?, ?, ?, ?)";
        Object[] parameter = {user.getUsername(), user.getPassword(), user.getAge(), user.getEmail()};
        
        int result = jdbcTemplate.update(sql, parameter);
        
        System.out.println("受影响行数:" + result);
        
        return result;
        
    }

UserDaoService.java

	//add
    public int addUser(User user){
    	
        int result = userDao.addUser(user);
        
        return result;
        
    }

test

	@Test
    public void testJdbcTemplateAddUser(){
    	
    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        
        
        User user = new User("宋江", "songjiang", 50, "9829021782qq.com");
        
        userService.addUser(user);
        
        classPathXmlApplicationContext.close();
        
    }

修改操作

int org.springframework.jdbc.core.JdbcTemplate.update(String sql, @Nullable Object... args) throws DataAccessException

UserDao.java

	//update;根据id进行修改
    int updateUserById(User user);

UserDaoImpl.java

	@Override
    public int updateUserById(User user) {
    	
        String sql = "update t_user set username=?, password=?, age=? where id=?";
    
        Object[] parameter = {user.getUsername(), user.getPassword(), user.getAge(), user.getId()};
        
        int result = jdbcTemplate.update(sql, parameter);
              
        System.out.println("受影响行数:" + result);
        
        return result;
        
    }

UserDaoService.java

	//update
    public int updateUserById(User user) {
    	
        int result = userDao.updateUserById(user);
        
        return result;
        
    }

test

	@Test
     public void testJdbcTemplateUpdateUserById(){
    	 
     	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
                
        User user = new User();
        user.setId(17);
        user.setUsername("卢俊义");
        user.setPassword("lujunyi");
        user.setAge(69);
        
        userService.updateUserById(user);
        
        classPathXmlApplicationContext.close();
              
    }

删除操作

int org.springframework.jdbc.core.JdbcTemplate.update(String sql, @Nullable Object... args) throws DataAccessException

UserDao.java

	//delete;根据id进行删除操作
    int deleteUserById(Integer id);

UserDaoImpl.java

	@Override
    public int deleteUserById(Integer id) {
    	
        String sql = "delete from t_user where id=?";
        
        int result = jdbcTemplate.update(sql, id);
        
        return result;
        
    }

UserDaoService.java

	public int deleteUserById(Integer id) {
        
    	return userDao.deleteUserById(id);
    	
    }

test

	@Test
      public void testJdbcTemplateDeleteUserById(){
    	  
     	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        int result = userService.deleteUserById(18);
        
        System.out.println("受影响行数:" + result);
        
        classPathXmlApplicationContext.close();
        
    }

查询操作

返回结果为值类型
<T> T org.springframework.jdbc.core.JdbcTemplate.queryForObject(String sql, Class<T> requiredType) throws DataAccessException

UserDao.java

	//查询总数
    int selectUserCount();

UserDaoImpl.java

	//查询记录数
    @Override
    public int selectUserCount() {
    	
        String sql = "select count(*) from t_user";
        
        /*
        Integer org.springframework.jdbc.core.JdbcTemplate.queryForObject(String sql, Class requiredType) throws DataAccessException
        
              第一个参数:sql语句
              第二个参数:返回类型的Class
        */
        return jdbcTemplate.queryForObject(sql, Integer.class);
        
    }

UserDaoService.java

	//select;查询表中的记录数
    public int selectUserCount(){
    	
        return userDao.selectUserCount();
        
    }

test

	@Test
	public void testJdbcTemplateFindCount() {

		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
		
		UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
		int count = userService.selectUserCount();

		System.out.println("查询的记录总数:" + count);

		classPathXmlApplicationContext.close();

	}
返回结果为对象类型
<T> T org.springframework.jdbc.core.JdbcTemplate.queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException

UserDao.java

	//根据id查询一条记录
    User selectUserById(Integer id);

UserDaoImpl.java

	/*
	第一个参数:sql语句
	第二个参数:RowMapper是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
	第三个参数:id
	*/
    @Override
    public User selectUserById(Integer id) {
    	
        String sql = "select * from t_user where id=?";
        
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        
        return jdbcTemplate.queryForObject(sql, rowMapper, id);
        
    }

UserDaoService.java

	//根据id查询一条数据
    public User selectUserById(Integer id) {
    	
        return userDao.selectUserById(id);
        
    }

test

	@Test
    public void testJdbcTemplateSelectUserById(){
    	
    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        User user = userService.selectUserById(2);
        
        System.out.println(user);
        
        classPathXmlApplicationContext.close();
        
    }
返回结果为List集合类型
<T> List<T> org.springframework.jdbc.core.JdbcTemplate.query(String sql, RowMapper<T> rowMapper) throws DataAccessException

UserDao.java

	//查询所有记录
    List<User> selectUserAll();

UserDaoImpl.java

	//查询所有记录
    @Override
    public List<User> selectUserAll() {
    	
        String sql = "select * from t_user";
        
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        
        return jdbcTemplate.query(sql, rowMapper);
        
        //return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        
    }

UserDaoService.java

	//查询所有记录
    public List<User> selectUserAll() {
    	
        return userDao.selectUserAll();
        
    }

test

	@Test
    public void testJdbcTemplateSelectUserAll(){
    	
    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        List<User> users = userService.selectUserAll();
        
        System.out.println(users);
        
        users.forEach(System.out::println);
        
        classPathXmlApplicationContext.close();
        
    }

批量操作

int[] org.springframework.jdbc.core.JdbcTemplate.batchUpdate(String sql, List<Object[]> batchArgs) throws DataAccessException

批量添加操作

UserDao.java

	int[] batchAddUser(List<Object[]> batchArgs);

UserDaoImpl.java

	//批量添加    
    @Override
    public int[] batchAddUser(List<Object[]> batchArgs) {
        
    	String sql = "insert into t_user values(null, ?, ?, ?, ?)";
    	
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        
        return ints;
        
    }

UserDaoService.java

	//批量添加
    public int[] batchAdd(List<Object[]> batchArgs) {
    	
        return userDao.batchAddUser(batchArgs);
        
    }

test

	//批量添加
    @Test
    public void testBatchAddUser() {

    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);

        List<Object[]> batchArgs = new ArrayList<>();
        Object[] user = {"宋江", "songjiang", 50, "982902178@qq.com"};
        Object[] user1 = {"卢俊义", "lujunyi", 51, "982902178@qq.com"};
        Object[] user2 = {"吴用", "wuyong", 52, "982902178@qq.com"};

        batchArgs.add(user);
        batchArgs.add(user1);
        batchArgs.add(user2);

        //调用批量添加方法
        int[] ints = userService.batchAdd(batchArgs);
        
        for(int i=0; i<ints.length; i++) {
        	System.out.println(ints[i]);
        }
        
        System.out.println("***********");
        
        System.out.println(Arrays.toString(ints));
        
        classPathXmlApplicationContext.close();
        
   }

批量修改操作

UserDao.java

	int[] batchUpdateUser(List<Object[]> batchArgs);

UserDaoImpl.java

	//批量修改
    @Override
    public int[] batchUpdateUser(List<Object[]> batchArgs) {
    	
        String sql = "update t_user set username=?, password=?, age=? where id=?";

        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        
        return ints;
        
    }

UserDaoService.java

	//批量修改
    public int[] batchUpdateUser(List<Object[]> batchArgs) {
    	
        return userDao.batchUpdateUser(batchArgs);
        
    }

test

	//批量修改操作
    @Test
    public void testBatchUpdateUser() {

    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] user = {"宋江1", "songjiang1", 60, 19};
        Object[] user1 = {"卢俊义1", "lujunyi1", 61, 20};
        Object[] user2 = {"吴用1", "wuyong1", 62, 21};

        batchArgs.add(user);
        batchArgs.add(user1);
        batchArgs.add(user2);

        //调用批量修改方法
        int[] ints = userService.batchUpdateUser(batchArgs);
        
        System.out.println(Arrays.toString(ints));
        
        classPathXmlApplicationContext.close();
        
    }

批量删除操作

UserDao.java

	//批量删除操作
    int[] batchDeleteUser(List<Object[]> batchArgs);

UserDaoImpl.java

	//批量删除
    @Override
    public int[] batchDeleteUser(List<Object[]> batchArgs) {

        String sql = "delete from t_user where id=?";

        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        
        return ints;
        
    }

UserDaoService.java

	//批量删除
    public int[] batchDeleteUser(List<Object[]> batchArgs) {
    	
        return userDao.batchDeleteUser(batchArgs);
        
    }

test

	//批量删除
    @Test
    public void testBatchDelete() {

    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");     
    	UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);

        List<Object[]> batchArgs = new ArrayList<>();
        Object[] object = {19};
        Object[] object1 = {20};
        Object[] object2 = {21};
        
        batchArgs.add(object);
        batchArgs.add(object1);
        batchArgs.add(object2);

        //调用批量修改方法
        int[] ints = userService.batchDeleteUser(batchArgs);
    
        System.out.println(Arrays.toString(ints));
        
        classPathXmlApplicationContext.close();
        
    }

完整代码
UserDao.java

package com.jack.spring.jdbc_template.dao;

import java.util.List;

import com.jack.spring.jdbc_template.entity.User;

public interface UserDao {

    //add
    int addUser(User user);

    //update;根据id进行修改
    int updateUserById(User user);

    //delete;根据id进行删除操作
    int deleteUserById(Integer id);

    //查询总数
    int selectUserCount();

    //根据id查询一条记录
    User selectUserById(Integer id);

    //查询所有记录
    List<User> selectUserAll();

    //批量添加操作
    int[] batchAddUser(List<Object[]> batchArgs);

    //批量修改操作
    int[] batchUpdateUser(List<Object[]> batchArgs);

    //批量删除操作
    int[] batchDeleteUser(List<Object[]> batchArgs);

}

UserDaoImpl.java

package com.jack.spring.jdbc_template.dao;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.jack.spring.jdbc_template.entity.User;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao{

    //@Autowired
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public int addUser(User user) {
    	
        //调用JdbcTemplate中的update()可以对数据库表进行add,update,delete操作
        //第一个参数:sql语句;第二个参数:可变参数,设置 sql 语句值
        String sql = "insert into t_user values (null, ?, ?, ?, ?)";
        Object[] parameter = {user.getUsername(), user.getPassword(), user.getAge(), user.getEmail()};
        
        int result = jdbcTemplate.update(sql, parameter);
        
        System.out.println("受影响行数:" + result);
        
        return result;
        
    }

    @Override
    public int updateUserById(User user) {
    	
        String sql = "update t_user set username=?, password=?, age=? where id=?";
    
        Object[] parameter = {user.getUsername(), user.getPassword(), user.getAge(), user.getId()};
        
        int result = jdbcTemplate.update(sql, parameter);
              
        System.out.println("受影响行数:" + result);
        
        return result;
        
    }

    @Override
    public int deleteUserById(Integer id) {
    	
        String sql = "delete from t_user where id=?";
        
        int result = jdbcTemplate.update(sql, id);
        
        return result;
        
    }

    //查询记录数
    @Override
    public int selectUserCount() {
    	
        String sql = "select count(*) from t_user";
        
        /*
        Integer org.springframework.jdbc.core.JdbcTemplate.queryForObject(String sql, Class requiredType) throws DataAccessException
        
              第一个参数:sql语句
              第二个参数:返回类型的Class
        */
        return jdbcTemplate.queryForObject(sql, Integer.class);
        
    }

    /*
	第一个参数:sql语句
	第二个参数:RowMapper是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
	第三个参数:id
	*/
    @Override
    public User selectUserById(Integer id) {
    	
        String sql = "select * from t_user where id=?";
        
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        
        return jdbcTemplate.queryForObject(sql, rowMapper, id);
        
    }

    //查询所有记录
    @Override
    public List<User> selectUserAll() {
    	
        String sql = "select * from t_user";
        
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        
        return jdbcTemplate.query(sql, rowMapper);
        
        //return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        
    }

    //批量添加    
    @Override
    public int[] batchAddUser(List<Object[]> batchArgs) {
        
    	String sql = "insert into t_user values(null, ?, ?, ?, ?)";
    	
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        
        return ints;
        
    }

    //批量修改
    @Override
    public int[] batchUpdateUser(List<Object[]> batchArgs) {
    	
        String sql = "update t_user set username=?, password=?, age=? where id=?";

        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        
        return ints;
        
    }

    //批量删除
    @Override
    public int[] batchDeleteUser(List<Object[]> batchArgs) {

        String sql = "delete from t_user where id=?";

        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        
        return ints;
        
    }

}

UserService.java

package com.jack.spring.jdbc_template.service;

import org.springframework.stereotype.Service;

import com.jack.spring.jdbc_template.dao.UserDao;
import com.jack.spring.jdbc_template.entity.User;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {

    //注入dao
    //@Autowired
    //@Qualifier(value = "BookDaoImpl")
    @Resource
    private UserDao userDao;

    //add
    public int addUser(User user){
    	
        int result = userDao.addUser(user);
        
        return result;
        
    }

    //update
    public int updateUserById(User user) {
    	
        int result = userDao.updateUserById(user);
        
        return result;
        
    }

    //delete
    public int deleteUserById(Integer id) {
        
    	return userDao.deleteUserById(id);
    	
    }

    //select;查询表中的记录数
    public int selectUserCount(){
    	
        return userDao.selectUserCount();
        
    }

    //根据id查询一条数据
    public User selectUserById(Integer id) {
    	
        return userDao.selectUserById(id);
        
    }

    
    //查询所有记录
    public List<User> selectUserAll() {
    	
        return userDao.selectUserAll();
        
    }
    
    //批量添加
    public int[] batchAdd(List<Object[]> batchArgs) {
    	
        return userDao.batchAddUser(batchArgs);
        
    }

    //批量修改
    public int[] batchUpdateUser(List<Object[]> batchArgs) {
    	
        return userDao.batchUpdateUser(batchArgs);
        
    }

    //批量删除
    public int[] batchDeleteUser(List<Object[]> batchArgs) {
    	
        return userDao.batchDeleteUser(batchArgs);
        
    }

}

test

package com.jack.spring.jdbc_template.test;

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

import com.jack.spring.jdbc_template.entity.User;
import com.jack.spring.jdbc_template.service.UserService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestUser {

	@Test
	public void testJdbcTemplateAddUser() {

		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
		
		UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);

		User user = new User("宋江", "songjiang", 50, "9829021782qq.com");

		userService.addUser(user);

		classPathXmlApplicationContext.close();

	}

	@Test
	public void testJdbcTemplateUpdateUserById() {

		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
		
		UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);

		User user = new User();
		user.setId(17);
		user.setUsername("卢俊义");
		user.setPassword("lujunyi");
		user.setAge(69);

		userService.updateUserById(user);

		classPathXmlApplicationContext.close();

	}

	@Test
	public void testJdbcTemplateDeleteUserById() {

		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
		
		UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
		int result = userService.deleteUserById(18);

		System.out.println("受影响行数:" + result);

		classPathXmlApplicationContext.close();

	}

	@Test
	public void testJdbcTemplateFindCount() {

		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
		
		UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
		int count = userService.selectUserCount();

		System.out.println("查询的记录总数:" + count);

		classPathXmlApplicationContext.close();

	}
	

    @Test
    public void testJdbcTemplateSelectUserById(){
    	
    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        User user = userService.selectUserById(2);
        
        System.out.println(user);
        
        classPathXmlApplicationContext.close();
        
    }

    @Test
    public void testJdbcTemplateSelectUserAll(){
    	
    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        List<User> users = userService.selectUserAll();
        
        System.out.println(users);
        
        users.forEach(System.out::println);
        
        classPathXmlApplicationContext.close();
        
    }

    //批量添加
    @Test
    public void testBatchAddUser() {

    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);

        List<Object[]> batchArgs = new ArrayList<>();
        Object[] user = {"宋江", "songjiang", 50, "982902178@qq.com"};
        Object[] user1 = {"卢俊义", "lujunyi", 51, "982902178@qq.com"};
        Object[] user2 = {"吴用", "wuyong", 52, "982902178@qq.com"};

        batchArgs.add(user);
        batchArgs.add(user1);
        batchArgs.add(user2);

        //调用批量添加方法
        int[] ints = userService.batchAdd(batchArgs);
        
        for(int i=0; i<ints.length; i++) {
        	System.out.println(ints[i]);
        }
        
        System.out.println("***********");
        
        System.out.println(Arrays.toString(ints));
        
        classPathXmlApplicationContext.close();
        
   }
    

    //批量修改操作
    @Test
    public void testBatchUpdateUser() {

    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] user = {"宋江1", "songjiang1", 60, 19};
        Object[] user1 = {"卢俊义1", "lujunyi1", 61, 20};
        Object[] user2 = {"吴用1", "wuyong1", 62, 21};

        batchArgs.add(user);
        batchArgs.add(user1);
        batchArgs.add(user2);

        //调用批量修改方法
        int[] ints = userService.batchUpdateUser(batchArgs);
        
        System.out.println(Arrays.toString(ints));
        
        classPathXmlApplicationContext.close();
        
    }

    //批量删除
    @Test
    public void testBatchDelete() {

    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\jdbc_template\\xml\\bean.xml");     
    	UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);

        List<Object[]> batchArgs = new ArrayList<>();
        Object[] object = {19};
        Object[] object1 = {20};
        Object[] object2 = {21};
        
        batchArgs.add(object);
        batchArgs.add(object1);
        batchArgs.add(object2);

        //调用批量修改方法
        int[] ints = userService.batchDeleteUser(batchArgs);
    
        System.out.println(Arrays.toString(ints));
        
        classPathXmlApplicationContext.close();
        
    }

}

事务

事务的四个特性(ACID )
(1)原子性
(2)一致性
(3)隔离性
(4)持久性

创建表;表名:t_account

字段名称类型长度备注
idbigint20主键自增
usernamevarchar255
moneyint11

创建UserDao.java

package com.jack.spring.transaction.dao;

public interface UserDao {

    //多钱
    int addMoney();
    
    //少钱
    int reduceMoney();

}

创建UserDaoImpl.java

package com.jack.spring.transaction.dao;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository
public class UserDaoImpl implements UserDao{

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public int reduceMoney() {

        String sql = "update t_account set money=money-? where username=?";
        
        return jdbcTemplate.update(sql, 10, "宋江");

    }

    @Override
    public void addMoney() {

        String sql = "update t_account set money=money+? where username=?";
        
        return jdbcTemplate.update(sql, 10, "卢俊义");

    }

}

UserService.java

package com.jack.spring.transaction.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.jack.spring.transaction.dao.UserDao;

import javax.annotation.Resource;

@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ) // 这个注解可以添加到类上面(表示类里所有的方法都开启事务),也可以添加到方法上面(只把此方法开启事务);开启事务,里面的值都是默认的
public class UserService {

	// 注入dao
	@Resource
	private UserDao userDao;

	// 转账的方法
	public intaccountMoney() {

		int resultReduce = userDao.reduceMoney();
		
		//int i = 10/0; //执行了事务的回滚

		int resultAdd useDao.addMoney();

		return resultReduce + resultAdd;
		 
	}

}

test

	@Test
    public void testUserAccount() {

    	ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("com\\jack\\spring\\transaction\\xml\\bean.xml");
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);

        userService.accountMoney();
        
        int result = userService.accountMoney();
        
        System.out.println(result);
 
        classPathXmlApplicationContext.close();
        
    }

异常处理:

	// 转账的方法
	public int accountMoney() {

		try {
			//第一步:开启事务
			
			//第二步:进行业务操作
			int resultReduce = userDao.reduceMoney();
			
			//模拟异常
			int i = 10/0;

			int resultAdd = userDao.addMoney();
			
			//第三步:没有发生异常,提交事务
			
			System.out.println(i);
			
			return resultReduce + resultAdd;
			
		}catch (Exception e) {

			//第四步:出现异常,事务回滚
			
			return 0;
			
		}
		
	}

事务管理

在Spring中进行事务管理的操作有两种方式:编程式事务管理和声明式事务管理。

声明式事务管理的两种方式:基于注解方式、基于xml配置文件方式。

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

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

基于注解方式

添加Spring事务管理:
1、创建事务管理器

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

2、开启事务注解
引入tx标签
xmlns:tx=“http://www.springframework.org/schema/tx”
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd

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

3、在UserService类上面或者UserService类里面的方法上面)添加事务注解@Transactional
(1)@Transactional,这个注解可以添加到类上面,也可以添加在方法上面。
(2)如果把这个注解添加在类上面,这个类里面所有的方法都添加事务管理。
(3)如果把这个注解添加在方法上面,为这个方法添加事务管理。

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

	<!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClass}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>      
    </bean>

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


    <!--开启组件扫描;使用注解方法进行注入-->
    <context:component-scan base-package="com.jack.spring.transaction"/>


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

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

声明式事务管理参数配置

在service层类上面添加注解@Transactional,在这个注解里面可以配置事务相关参数。
在这里插入图片描述

@AliasFor("transactionManager")
String value() default "";

@AliasFor("value")
String transactionManager() default "";

Propagation propagation() default Propagation.REQUIRED;

Isolation isolation() default Isolation.DEFAULT;

int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;

boolean readOnly() default false;

Class<? extends Throwable>[] rollbackFor() default {};

String[] rollbackForClassName() default {};

Class<? extends Throwable>[] noRollbackFor() default {};

String[] noRollbackForClassName() default {};
propagation:事务传播行为

事务传播行为:多事务方法直接进行调用,这个过程中事务是如何进行管理的。
事务方法:对数据库表数据进行变化的操作。

事务的传播行为可以由传播属性指定。Spring定义了7种类传播行为。

REQUIRED(TransactionDefinition.PROPAGATION_REQUIRED)
SUPPORTS(TransactionDefinition.PROPAGATION_SUPPORTS)
MANDATORY(TransactionDefinition.PROPAGATION_MANDATORY)
REQUIRES_NEW(TransactionDefinition.PROPAGATION_REQUIRES_NEW)
NOT_SUPPORTED(TransactionDefinition.PROPAGATION_NOT_SUPPORTED)
NEVER(TransactionDefinition.PROPAGATION_NEVER)
NESTED(TransactionDefinition.PROPAGATION_NESTED)
传播属性描述
REQUIRED如果有事务在运行,当前的方法就在这个事务内运行,否则,就启动一个新的事务,并在自己的事务内运行。
REQUIRES_NEW当前的方法必须启动新事务,并在它自己的事务内运行。如果有事务正在运行,应该将它挂起。
SUPPORTS如果有事务在运行,当前的方法就在这个事务内运行,否则它可以不运行在事务中。
NOT_SUPPORTED当前的方法不应该运行在事务中。如果有运行的事务,将它挂起。
MANDATORY当前的方法必须运行在事务内部,如果没有正在运行的事务,就抛出异常。
NEVER当前的方法不应该运行在事务中,如果有运行的事务,就抛出异常。
NESTED如果有事务在运行,当前的方法就应该在这个事务的嵌套事务内运行。否则,就启动一个新的事务,并在它自己的事务内运行。
ioslation:事务隔离级别
timeout:超时时间
readOnly:是否只读
rollbackFor:回滚

Spring

Spring是一个轻量级的IoC和AOP容器框架。是为Java应用程序提供基础性服务的一套框架,目的是用于简化企业应用程序的开发,它使得开发者只需要关心业务需求。常见的配置方式有三种:基于XML的配置、基于注解的配置、基于Java的配置。

主要由以下几个模块组成:

Spring Core:核心类库,提供IOC服务;

Spring Context:提供框架式的Bean访问方式,以及企业级功能(JNDI、定时任务等);

Spring AOP:AOP服务;

Spring DAO:对JDBC的抽象,简化了数据访问异常的处理;

Spring ORM:对现有的ORM框架的支持;

Spring Web:提供了基本的面向Web的综合特性,例如多方文件上传;

Spring MVC:提供面向Web应用的Model-View-Controller实现。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值