Spring

1、Spring概念

1.1 Spring简介

1、Spring是轻量级的开源的JaveEE框架
2、Spring可以解决企业应用开发的复杂性
3、Spring有两个核心部分:IOC 和 Aop
(1)IOC:控制反转,把创建对象过程交给Spring进行管理
(2)Aop:面向切面,不修改源代码进行功能增强
4、Spring特点

  • 方便解耦,简化开发
  • Aop编程支持
  • 方便程序测试
  • 方便与其他框架整合
  • 方便进行事物操作
  • 降低API开发难度

1.2 Spring下载流程

1.首先进入官网,找到spring framework点击 github图标
在这里插入图片描述
2.下拉找到 Access to Binaries
在这里插入图片描述
3.然后点击下图网址
在这里插入图片描述
4.依次点入
在这里插入图片描述
5.找到对应版本
在这里插入图片描述
6、复制链接下载在这里插入图片描述

1.3 第一个Spring程序

项目目录结构
在这里插入图片描述

1.3.1 idea新建maven项目

在这里插入图片描述

1.3.2 导入核心包

在这里插入图片描述
在这里插入图片描述
在主目录下创建lib目录,导入spring四个核心包

1.3.3 在pom.xml添加日志包

<dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
</dependency>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    
</project>

1.3.4 创建实体类User

package jlf.com;

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

1.3.5 创建配置文件bean.xml

在resource下创建bean1.xml
在这里插入图片描述
bean1.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="jlf.com.User">
    </bean>
</beans>

1.3.6 编写测试类

package jlf.com.test;

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

public class TestSpring {
    @Test
    public void testAdd(){
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

        // 2 获取配置创建的对象
        User user = context.getBean("user", User.class);

        System.out.println(user);
        user.add();
    }
}

运行结果:
在这里插入图片描述

2、IOC 容器

IOC (Inversion of Control):控制反转,是一个理论,概念,思想。
把对象的创建,赋值,管理工作都交给代码之外的容器实现,也就是对象的创建是有其它的外部 资源完成。

控制:创建对象,对象的属性赋值,对象之间的关系管理。

反转:把原理的开发人员管理,创建对象的权限转移给代码之外的容器实现。由容器代替开发人员管理对象。创建对象,给属性赋值

正转:由开发人员在代码中,使用new 构造方法创建对象,开发人员主动管理对象

public static void main(String[] args) {
        Student student = new Student;
    }

容器:是一个服务软件,一个框架 (Spring)

为什么要使用ioc: 目的就是减少对代码的改动,也能实现不同的功能。实现解耦合

2.1 IOC底层原理

xml解析、工厂模式、反射

原始创建对象的方式:
在这里插入图片描述

依赖:类a中 使用类b的属性或者方法,叫做class a依赖 class b

工厂模式:
在这里插入图片描述
IOC过程:
第一步: xml文件配置,配置创建的对象

 <bean id="dao" class="jlf.com.UserDao">

第二步 :有service类 和 dao类,创建工厂类

class UserFactory{
	public static UserDao getDao(){
		String classValue = class 属性值; // xml 解析
		Class clazz = Class.forName(classValue);   // 通过反射创建对象
		return (UserDao)class.newInstance();
   }
}

2.2 IOC接口

1、IOC思想基于IOC容器完成,IOC容器底层就是对象工厂。

2、Spring提供IOC容器实现两种方式:(两个接口)
(1) BeanFactory: IOC容器基本实现,是Spring内部的使用接口,不提供开发人员进行使用

  • 加载配置文件时候,不会创建对象,在获取对象的(使用)才去创建对象
    在这里插入图片描述

(2) ApplicationContext:BeanFactory 接口的子接口,提供更多更强大的功能,一般由开发人员使用

  • 加载配置文件时候就会把在配置文件的对象进行创建
    在这里插入图片描述
    查看 ApplicationContext 结构
    在这里插入图片描述

FIleSysetemxmlApplicationContext
参数 :c盘全路径

ClassPathXmlAppliccation
参数: 当前路径

2.3 IOC操作bean管理

2.3.1 什么是bean管理

Bean管理指的是两个操作:

  • Spring创建对象
  • Spring注入属性 (赋值 例如字段age, 给age赋值)

Bean管理操作有两种方式

  • 基于xml配置文件方式实现
  • 基于注解方式实现

2.3.2 IOC操作bean管理(基于xml方式)

1、基于xml方式创建对象

 <bean id="dao" class="jlf.com.UserDao">

(1)在spirng配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建

(2)在bean标签里有很多属性,介绍常用的属性

  • id属性:唯一标识
  • class属性:类全路径(包类路径)
  • name属性:现在已经不用了,早期给struts用的

(3)创建对象的时候,默认也是执行无参数构造方法完成对象创建

基于xml注入属性
(1) DI: 依赖注入,就是注入属性
第一种注入方式:使用set方法进行注入
在这里插入图片描述

第二种 有参数的构造注入
在这里插入图片描述

2.3.2.1 set注入

1、编写实体类

public class Student {
    private String name;

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

    public void testdemo(){
        System.out.println(name);
    }
}

2、编写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="jlf.com.User">-->

    <!--set方法进行属性注入-->
    <bean id="student" class="jlf.com.Student">
        <!--使用property 进行属性注入
            name:类属性里的名称
            value:向属性注入的值
        -->
        <property name="name" value="小红"/>
    </bean>
</beans>

name:类属性里的名称
value:向属性注入的值

3、编写测试类

public class TestSpring {

    @Test
    public void testStudent(){
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        // BeanFactory context = new ClassPathXmlApplicationContext("bean1.xml");

        // 2 获取配置创建的对象
        Student student = context.getBean("student",Student.class);
        System.out.println(student);
        student.testdemo();
    }
}
2.3.2.2 有参数的构造注入

1、创建实体类,定义属性,创建属性对应的构造方法

public class Teacher {
    private String sex;
    private String subject;

    public Teacher(String sex, String subject) {
        this.sex = sex;
        this.subject = subject;
    }

    public void testdemo(){
        System.out.println(sex+"::"+subject);
    }
}

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

<bean id="teacher" class="jlf.com.Teacher">
        <constructor-arg name="sex" value=""></constructor-arg>
        <constructor-arg name="subject" value="科学"></constructor-arg>
    </bean>

3、测试

@Test
    public void testTeacher(){
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        // BeanFactory context = new ClassPathXmlApplicationContext("bean1.xml");

        // 2 获取配置创建的对象
        // User user = context.getBean("user", User.class);
        Teacher teacher = context.getBean("teacher",Teacher.class);
        System.out.println(teacher);
        teacher.testdemo();
    }
2.3.2.3 p名称空间注入(了解即可)

本质上还是set注入

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

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

</beans>

第二步
进行属性注入,在bean标签里面进行操作

<?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 id="student" class="jlf.com.Student" p:name="小红">
    </bean>

</beans>
2.3.2.4 xml注入其他类型属性
2.3.2.4.1 字面量

(1) null值

<bean id="student" class="jlf.com.Student">
        <property name="name" value="小红"></property>
        <!--设置null值-->
        <property name="address">
            <null></null>
        </property>
    </bean>

(2) 属性值包含特殊符号

  • 转义
  • 把带特殊符号的内容写到CDATA
    例如写入地址为 <<南京>>
<bean id="student" class="jlf.com.Student">
        <property name="name" value="小红"></property>
        <!--null值-->
        <property name="address">
            <value><![CDATA[<<南京>>]]></value>
        </property>
    </bean>
2.3.2.4.2 注入属性-外部 bean

(1) 创建两个类 service类 和 dao 类

UserDao.java

package jlf.com.dao;

public interface UserDao {
    public void add();
}

UserDaoImpl.java

package jlf.com.dao;

public class UserDaoImpl implements UserDao{

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

UserService.java

package jlf.com.service;

import jlf.com.dao.UserDao;
import jlf.com.dao.UserDaoImpl;

public class UserService {

    public void up(){
        System.out.println("service up");

        // 原先创建UserDao对象方式
//         UserDao userDao = new UserDaoImpl();
//         userDao.add();
        // 现在用spring 创建

        userDao.add();
    }


    // 创建UserDao类型属性,生成set方法
    private UserDao userDao;

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

(2) 在service 调用 dao里面的方法
(3) 在spring配置文件中进行配置

    <bean id="userService" class="jlf.com.service.UserService">
        <!--注入userDao对象-->
        <!-- ref属性:创建userDao对象标签id值 -->
        <property name="userDao" ref="userDao"></property>
    </bean>
    <bean id="userDao" class="jlf.com.dao.UserDaoImpl"></bean>

测试类

public class TestBean {
    @Test
    public void testStudent(){
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");

        // 2 获取配置创建的对象
        // User user = context.getBean("user", User.class);
        UserService userService = context.getBean("userService",UserService.class);
        System.out.println(userService);
        userService.up();
    }
}

2.3.2.4.3 注入属性-内部 bean

(1) 一对多关系:部门和员工
一个部门有多个员工,一个员工属于一个部分

(2) 在实体类之间表示一对多关系,员工表示所属部门,使用对象类型属性进行表示
Dept.java

// 部门类
public class Dept {
    private String dname;

    public void setDname(String dname) {
        this.dname = dname;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "dname='" + dname + '\'' +
                '}';
    }
}

Emp.java

public class Emp {
    private String ename;
    private String gender;

   // 员工属于某一个部门,使用对象形式表示
    private Dept dept;

    public void setEname(String ename) {
        this.ename = ename;
    }

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

    public void setDept(Dept dept) {
        this.dept = dept;
    }
    public void add(){
        System.out.println(ename+"::"+gender+"::"+dept);
    }
}

(3) 在spring配置文件中进行配置

<!--内部bean-->
    <bean id="emp" class="jlf.com.bean.Emp">
        <!--设置两个普通属性  -->
        <property name="ename" value="小红"></property>
        <property name="gender" value=""></property>

        <property name="dept">
            <bean id="dept" class="jlf.com.bean.Dept">
                <property name="dname" value="安全部"></property>
            </bean>
        </property>
    </bean>

测试类

 @Test
    public void testStudent(){
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");

        // 2 获取配置创建的对象
        // User user = context.getBean("user", User.class);
        Emp emp = context.getBean("emp",Emp.class);
        System.out.println(emp);
        emp.add();
    }
2.3.2.4.4 注入属性-级联赋值

第一种方法
外部bean,外部赋值

    <bean id="emp" class="jlf.com.bean.Emp">
        <!--设置两个普通属性  -->
        <property name="ename" value="小红"></property>
        <property name="gender" value=""></property>
        <!--级联赋值-->
        <property name="dept" ref="dept">
        </property>
    </bean>
    <bean id="dept" class="jlf.com.bean.Dept">
        <property name="dname" value="财务部"></property>
    </bean>

第二种方法

    <bean id="emp" class="jlf.com.bean.Emp">
        <!--设置两个普通属性  -->
        <property name="ename" value="小红"></property>
        <property name="gender" value=""></property>
        <!--级联赋值-->
        <property name="dept" ref="dept"> </property>
        <property name="dept.dname" value="技术部"></property>
    </bean>
    <bean id="dept" class="jlf.com.bean.Dept">
        <property name="dname" value="财务部"></property>
    </bean>

这里dname需要生成getter方法,不然得不到属性会报错。

2.3.2.5 注入集合属性
2.3.2.5.1 注入list,set,map ,数组
  • 注入数组类型属性
  • 注入List类型属性
  • 注入Map类型属性

(1) 创建类,定义数组、list、map、set类型属性,生成对应的set方法

package jlf.com.collectiontype;

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

public class Stu {
    // 数组类型属性
    private String[] course;

    // list集合属性
    private List<String> list;

    // map属性集合
    private Map<String,String> maps;

    // set属性集合
    private Set<String> sets;

    public void setCourse(String[] course) {
        this.course = course;
    }

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

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public void setSets(Set<String> sets) {
        this.sets = sets;
    }

    public void test(){
        System.out.println(Arrays.toString(course));
        System.out.println(list);
        System.out.println(maps);
        System.out.println(sets);
    }
}

(2) 在spring配置文件进行配置

<?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="stu" class="jlf.com.collectiontype.Stu">
        <!--数组类型的属性注入-->
        <property name="course">
            <array>
                <value>java</value>
                <value>数据库</value>
            </array>
        </property>
        <!--List类型的属性注入-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>小三</value>
            </list>
        </property>
        <!--Map类型的属性注入-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>
        <!--Set类型的属性注入-->
        <property name="sets">
            <set>
                <value>Mysql</value>
                <value>Redis</value>
            </set>
        </property>
    </bean>
</beans>

(3) 测试类

@Test
public void testStudent(){
    // 1 加载spring配置文件
    ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");

    // 2 获取配置创建的对象
    // User user = context.getBean("user", User.class);
    Stu stu = context.getBean("stu",Stu.class);
    System.out.println(stu);
    stu.test();
}
2.3.2.5.2 在集合里注入对象类型值

1、新增Course.java

package jlf.com.collectiontype;

public class Course {
    private String cname;

    @Override
    public String toString() {
        return "Course{" +
                "cname='" + cname + '\'' +
                '}';
    }

    public void setCname(String cname) {
        this.cname = cname;
    }
}

2、在刚刚的Stu.java 新增加 courses字段
在这里插入图片描述

3、修改刚刚的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="stu" class="jlf.com.collectiontype.Stu">
        <!--数组类型的属性注入-->
        <property name="course">
            <array>
                <value>java</value>
                <value>数据库</value>
            </array>
        </property>
        <!--List类型的属性注入-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>小三</value>
            </list>
        </property>
        <!--Map类型的属性注入-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>
        <!--Set类型的属性注入-->
        <property name="sets">
            <set>
                <value>Mysql</value>
                <value>Redis</value>
            </set>
        </property>

        <property name="courses">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>
    </bean>

    <bean id="course1" class="jlf.com.collectiontype.Course">
        <property name="cname" value="Spring5框架"></property>
    </bean>

    <bean id="course2" class="jlf.com.collectiontype.Course">
        <property name="cname" value="Mybatis框架"></property>
    </bean>
</beans>
2.3.2.5.3 提取集合注入的部分

(1)新建Book类
Book.java

public class Book {
    private List<String> list;

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

    public void test(){
        System.out.println(list);
    }
}

(2)在spirng配置文件中引入名称空间util

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

</beans>

(3)使用util标签

<?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="bookList">
        <value>java面向对象</value>
        <value>程序员的自我修养</value>
        <value>三国演义</value>
    </util:list>

    <!--提取list集合类型注入使用-->
    <bean id="book" class="jlf.com.collectiontype.Book">
        <property name="list" ref="bookList"></property>
    </bean>
</beans>

(4)和之前一样编写测试类

2.3.2.6 两种类型bean

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

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

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

第一步 创建类,让这个类作为工厂bean,实现接口FactoryBean

public class MyBean implements FactoryBean<Course> {

    // 定义返回bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("asd");
        return course;
    }

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

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

第二步 实现接口里面的方法,在实现的方法中定义返回bean类型

@Test
public void testStudent(){
    // 1 加载spring配置文件
    ApplicationContext context = new ClassPathXmlApplicationContext("bean5.xml");

    // 2 获取配置创建的对象
    // User user = context.getBean("user", User.class);
    Course course =context.getBean("myBean",Course.class);
    // MyBean myBean = context.getBean("myBean",MyBean.class);
    System.out.println(course);

}
2.3.2.7 bean的作用域

1、在Spring里面,设置创建bean实例是单实例还是多实例

2、在Spring里面,默认情况下,bean是单实例对象
在这里插入图片描述

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

(3)singleton 和 prototype 区别
第一 singleton 单实例,prototype多实例
第二 设置scope值是singleton时候,加载spring配置文件就会创建 单实例对象
设置scope值是prototype时候,不是在加载spring配置文件时候创建对象,在调用getBean方法的时候创建多实例对象

<bean id="dog" class="jlf.com.facbean.Dog" scope="prototype"></bean>

在这里插入图片描述

2.3.2.8 bean的生命周期

1、生命周期
(1) 从对象创建到对象销毁的过程

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

3、演示bean生命周期
Order.jave

public class Orders {
    // 无参数的构造
    public Orders() {
        System.out.println("第一步 执行无参数的bean实例");
    }

    private String oname;

    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步 调用set方法设置属性值");
    }

    public void init(){
        System.out.println("第三步 执行初始化的方法");
    }

    public void destory(){
        System.out.println("第五步 执行销毁的方法");
    }
}

xml

<bean id="orders" class="jlf.com.bean.Orders" init-method="init" destroy-method="destory">
        <property name="oname" value="手机"></property>
</bean>

Test.java

    @Test
    public void testStudent(){
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean7.xml");
        
        Orders orders = context.getBean(Orders.class);
        System.out.println("第四步 获取创建bean实例对象");
        System.out.println(orders);

        // 手动让bean实例销毁   才会执行bean中配置的 destory方法
        ((ClassPathXmlApplicationContext)context).close();
       }

4、bean的后置处理器,bean的生命周期一共有7步

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

5、演示
新建MyBeanPost类 实现 BeanPostProcessor接口

public class MyBeanPost 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;
    }
}

xml文件

    <bean id="orders" class="jlf.com.bean.Orders" init-method="init" destroy-method="destory">
        <property name="oname" value="手机"></property>
    </bean>

    <!--配置后置处理器-->
    <bean id="myBeanPost" class="jlf.com.bean.MyBeanPost"></bean>
2.3.2.9 xml自动装配

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

2、自动装配的过程
(1)根据属性名称进行注入

   <!--实现自动装配
        bean标签属性autowire,配置自动装配
        autowire属性常用两个值: byName更具属性名称注入 ,注入值bean的id值和类属性名称一样
         byType根据属性类型注入
    -->
  <bean id="emp" class="jlf.com.autowire.Emp" autowire="byName">
    </bean>
    <bean id="dept" class="jlf.com.autowire.Dept"></bean>

(2)根据属性类型进行注入

  <bean id="emp" class="jlf.com.autowire.Emp" autowire="byType">
    </bean>
    <bean id="dept" class="jlf.com.autowire.Dept"></bean>

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

2.3.2.10 xml引入外部属性文件

1、直接配置数据库信息
(1) 配置 德鲁伊 连接池
(2) 引入德鲁伊 连接池依赖 jar 包

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

2.3.3 基于注解方式

2.3.3.1 什么是注解
  • 注解是代码特殊标记,格式:@注解名称 (属性名称=属性值,属性名称=属性值)

  • 使用注解:注解作用在上面,方法上面,属性上面

  • 使用注解目的:简化xml配置

Spring常用针对 Bean管理中创建对象的注解

  • @Component
  • @Service
  • @Contorller
  • @Repository

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

2.3.3.2 基于注解方式实现对象创建

第一步 引入依赖 aop
在这里插入图片描述
第二步 开启组件扫描

如果要扫描多个包

  • 多个包使用逗号隔开
  • 写扫描包的上层目录
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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 如果要扫描多个包,多个包使用逗号隔开 <context:component-scan base-package="jlf.com.dao,jlf.com.service"></context:component-scan>
        2 写扫描包的上层目录 <context:component-scan base-package="jlf.com"></context:component-scan>
    -->
    <context:component-scan base-package="jlf.com"></context:component-scan>
</beans>

第三步 创建类,在类上添加创建对象注解

// 在注解里面 value 属性值可以省略不写
// 默认值是类名称,首字母小写
// UserService -- userService
@Component(value = "userService") // <bean id="userService" class=""></bean>
public class UserService {

    public void up(){
        System.out.println("service up");
    }
}

测试代码

  @Test
    public void testStudent(){
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean9.xml");

        UserService userService = context.getBean("userService", UserService.class);

        System.out.println(userService);
        userService.up();

    }

在第三步中,可以开启组件扫描细节配置
刚刚我们配置的xml中 jlf.com 扫描了该路径下的全部类,那么如何只扫描一部分

<context:component-scan base-package="jlf.com"></context:component-scan>

示例1

use-default-filters="false"表示现在不使用默认filter,自己配置filter
context:exclude-filter表示扫描哪些内容 ,type="annotation"表示根据注解扫描

<context:component-scan base-package="jlf.com" use-default-filters="false">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>
</context:component-scan>

该示例表示只扫描Component
示例2

<context:component-scan base-package="jlf.com">
     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

该示例表示不扫描Controller

2.3.3.3 基于注解的依赖注入

注入对象:
@Autowired :根据属性类型进行自动装配
@Qualifier : 根据属性名称进行注入
@Resource : 可以根据类型注入,可以根据名称注入
注入属性:
@Value :注入普通类型属性

@Autowired注入示例
@Autowired示例: 在UserService类型中创建UserDao
UserService.java

@Component(value = "userService") // <bean id="userService" class=""></bean>
public class UserService {

    //定义dao类型属性
    //不需要添加set方法
    //添加注入属性注解
    @Autowired		// 根据类型进行注入
    private UserDao userDao;

    public void up(){
        System.out.println("service up");
        userDao.add();
    }
}

@Qualifier注入示例
@Qualifier:根据属性名称进行注入 (一个接口可能有多个实现类)
需要和@Autowired 一起使用
UserService.java

@Component(value = "userService") // <bean id="userService" class=""></bean>
public class UserService {

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

    public void up(){
        System.out.println("service up");
        userDao.add();
    }
}

UserDaoImpl.java

@Repository(value = "userDaoImpl2")
public class UserDaoImpl implements UserDao{

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

@Resource注入示例
根据类型进行注入

@Component(value = "userService") // <bean id="userService" class=""></bean>
public class UserService {

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

    public void up(){
        System.out.println("service up");
        userDao.add();
    }
}

根据名称进行注入

@Component(value = "userService") // <bean id="userService" class=""></bean>
public class UserService {

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

    public void up(){
        System.out.println("service up");
        userDao.add();
    }
}

@Value注入示例


public class UserService {
    @Value(value = "abc")
    private String sname;

    public void up(){
        System.out.println(sname);
    }
}
2.3.3.4 完全注解开发

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

@Configuration // 作为配置类,代替xml配置文件
@ComponentScan(basePackages = {"jlf.com"})  // 开启组件扫描,包路径
public class SpringConfig {

}

(2) 编写测试类
原先的测试方法

  @Test
    public void testStudent(){
        // 1 加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean9.xml");

        UserService userService = context.getBean("userService", UserService.class);

        System.out.println(userService);
        userService.up();

    }

新的测试类

    @Test
    public void testStudent(){
        // 1 加载spring配置文件
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

        UserService userService = context.getBean("userService", UserService.class);

        System.out.println(userService);
        userService.up();

    }

把new ClassPathXmlApplicationContext(“bean9.xml”)改成了 new AnnotationConfigApplicationContext(SpringConfig.class)

3、AOP

3.1 AOP思想概述

AOP(概念)
1、什么是AOP
AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低。
在这里插入图片描述
例如上述两个类都实现了重复的方法 开启事物提交事物,在真实场景中,我们真正需要该的代码,只有 保存数据 这一部分。
在这里插入图片描述
这时候我们就可以把公共的部分抽取出来,然后再其他代码用的时候在切进去

3.2 AOP底层原理

关键词,代理模式

代理模式分为两种:
(1) (有接口情况)接口代理 : JDK动态代理

(2) (无接口情况)子类代理 : CGLIB 子类代理

需求: UserService业务类,有sava,update方法,希望在save,update方法执行之前记录日志。

3.2.1 JDK 动态代理

JDKProxyUtil.java

public class JDKProxyUtil {

    // 使用JDK动态代理获取第代理对象
    public static Object getProxy(final Object target){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), // 和目标对象一样的类加载器
                target.getClass().getInterfaces(), // 目标对象的接口列表
                new InvocationHandler() {
                    //这个方法在每次调用代理类对象的时候被执行
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("记录日志");

                        // 调用目标对象的方法

                        return method.invoke(target,args);
                    }
                });
    }
}

CustomerServiceImpl.java

public class CustomerServiceImpl implements CustomerService {
    @Override
    public void save() {
        System.out.println("开始");
    }

    @Override
    public void delete() {
        System.out.println("结束");
    }
}

测试

 @Test
    public void test1() {
        // 目标对象
        CustomerServiceImpl customerServiceImpl = new CustomerServiceImpl();

        //获取JDK动态代理接口
        CustomerService proxy = (CustomerService) JDKProxyUtil.getProxy(customerServiceImpl);
        //customerServiceImpl.save();
        //customerServiceImpl.delete();

        proxy.save();
        proxy.delete();
    }

3.2.1 CGLIB 子类代理

如果目标对象没有接口,那么只能子类代理

子类代理 Cglib

第一步 导入Cglib 的jar包
第二步 编写工具类 CglibProxyUtils.java

public class CglibProxyUtils {

    public static Object getProxy(Object target){
        return Enhancer.create(CustomerServiceImpl.class, new MethodInterceptor() {
            // intercept: 每次代理类对象执行方法的时候执行该方法
            @Override
            public Object intercept(Object o, Method method, Object[] arg2, MethodProxy methodProxy) throws Throwable {
                System.out.println("记录日志");
                // 调用目标对象的方法
                method.invoke(target,arg2);
                return null;
            }
        });
    }
}

这里的CustomerServiceImpl变为 (没有继承CustomerService)

public class CustomerServiceImpl {

    public void save() {
        System.out.println("开始");
    }

    public void delete() {
        System.out.println("结束");
    }
}

第三步 编写测试代码

    @Test
    public void test1() {
        // 目标对象
        CustomerServiceImpl customerServiceImpl = new CustomerServiceImpl();

        //获取JDK动态代理接口
        CustomerServiceImpl  proxy = (CustomerServiceImpl) CglibProxyUtils.getProxy(customerServiceImpl);

        proxy.save();
        proxy.delete();
    }

3.3 AOP术语介绍

  • 目标对象 (Tatget)
  • 代理对象 (Proxy)
  • 连接点 (Joinpoint)
  • 切入点 (Pointcut)
  • 通知 (增强) (Advice)
  • 切面 (Aspect、 Advisor)
  • 织入(切入) (Weaving)

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值