目 录CONTENT

文章目录

spring的IOC容器(2)

Eric
2022-02-15 / 0 评论 / 0 点赞 / 154 阅读 / 7,679 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2023-12-12,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

1 概念和原理

1.1 什么是IOC?

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

  • 使用IOC的目的:为了降低耦合度。

1.2 IOC的底层原理

  • xml解析、工厂设计模式、反射。

2 IOC接口(BeanFactory)

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

  • Spring提供IOC容器实现的两种方式:

    • BeanFactory:
      • IOC容器最基本的实现方式,是Spring内部的使用接口,不提供开发人员进行使用。
      • 加载配置文件的时候不会去创建对象,而是在获取对象(或使用对象)的时候才去创建对象。
    • ApplicationContext:
      • BeanFactory接口的子接口,提供更多更强大的功能,一般是由开发人员进行使用的。
      • 加载配置的文件的时候就会立即创建对象。
      • ApplicationContext接口的实现类。

3 IOC操作Bean管理

3.1 什么是Bean管理?

  • Bean管理指的是Spring创建对象和Spring注入属性。

3.2 Bean管理的操作有两种实现方法

  • 基于XML配置文件方式实现。

  • 基于注解方式实现。

3.3 基于XML方式进行Bean管理的操作

3.3.1 基于XML方式创建对象
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
        在Spring配置文件中,使用bean标签,标签中添加对应的属性即可,就可以实现对象的创建。
    在Bean标签中有很多属性,如下是一些常用的属性:
      - id属性:唯一标识。
      - class属性:类的全路径。 
    创建对象的时候,默认是调用的是无参构造方法。
    -->
    <bean id="user" class="top.open1024.spring.User"></bean>

</beans>
3.3.2 基于XML方式注入属性
  • DI:依赖注入,就是注入属性。
3.3.2.1 创建对象和使用Setter方法进行注入
  • Book.java
package top.open1024.spring;

public class Book {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • applicationContext.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="book" class="top.open1024.spring.Book">
       <!--
      使用property完成属性注入
        name:类里面属性名称
        value:向属性中注入的值
    -->
       <property name="name" value="红楼梦"/>
   </bean>

</beans>
  • 测试
package top.open1024.spring;

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

public class BookTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        System.out.println("book.getName() = " + book.getName());
    }

}
3.3.2.2 有参构造注入属性
  • Book.java
package top.open1024.spring;
public class Book {
    private String name;

    public Book(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
  • applicationContext.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="book" class="top.open1024.spring.Book" >
       <constructor-arg name="name" value="西游记"/>
   </bean>

</beans>
  • 测试
package top.open1024.spring;

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

public class BookTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        System.out.println("book.getName() = " + book.getName());
    }
}
3.3.2.3 p名称空间注入

p名称空间注入,可以简化Setter方法注入

  • Book.java
package top.open1024.spring;

public class Book {

    private String name;

    private Double price;

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
  • applicationContext.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: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="book" class="top.open1024.spring.Book" p:name="红楼梦" p:price="20">
    </bean>

</beans>
  • 测试
package top.open1024.spring;

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

public class BookTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        System.out.println("book = " + book);
    }
}
3.3.2.4 注入null和特殊字符
  • Book.java
package top.open1024.spring;

public class Book {

    private String name;

    private Double price;

    private String address;

    public String getAddress() {
        return address;
    }

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

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", address='" + address + '\'' +
                '}';
    }
}
  • applicationContext.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: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="book" class="top.open1024.spring.Book">
        <!--
            null值
        -->
        <property name="name">
            <null></null>
        </property>
        <!-- 属性值包含特殊字符 -->
        <property name="address">
            <value><![CDATA[<<江苏>>]]]></value>
        </property>
    </bean>
</beans>
  • 测试
package top.open1024.spring;

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

public class BookTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        System.out.println("book = " + book);
    }
}
3.3.2.5 注入属性-外部Bean
  • UserDao.java
package top.open1024.spring.dao;

public interface UserDao {

    public void update();

}
  • UserDaoImpl.java
package top.open1024.spring.dao.impl;

import top.open1024.spring.dao.UserDao;

public class UserDaoImpl implements UserDao {

    @Override
    public void update() {
        System.out.println("dao update....");
    }
}
  • UserService.java
package top.open1024.spring.service;

import top.open1024.spring.dao.UserDao;

public class UserService {

    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

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

    public void update(){
        System.out.println("service update...");
        userDao.update();
    }
}
  • applicationContext.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: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="userDao" class="top.open1024.spring.dao.impl.UserDaoImpl"></bean>
    <bean id="userService" class="top.open1024.spring.service.UserService">
        <property name="userDao" ref="userDao"></property>
    </bean>
</beans>
  • 测试
package top.open1024.spring;

import top.open1024.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserServiceTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.update();
    }
}
3.3.2.6 注入属性-内部Bean
  • Dept.java
package top.open1024.spring;

import java.io.Serializable;

/**
 * 部门
 */
public class Dept implements Serializable {

    /**
     * 部门名称
     */
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Dept{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • Employee.java
package top.open1024.spring;

import java.io.Serializable;

/**
 * 员工
 */
public class Employee implements Serializable {

    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String gender;

    /**
     * 一个员工属于一个部门
     */
    private Dept dept;

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

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

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", dept=" + dept +
                '}';
    }
}
  • applicationContext.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: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="emp" class="top.open1024.spring.Employee">
        <property name="name" value="张三"/>
        <property name="gender" value="男"/>
        <!--
            设置内部Bean
        -->
        <property name="dept">
            <bean id="dept" class="top.open1024.spring.Dept">
                <property name="name" value="开发部"/>
            </bean>
        </property>
    </bean>
</beans>
  • 测试:
package top.open1024.spring;

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

public class EmployeeTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Employee employee = context.getBean("emp", Employee.class);
        System.out.println("employee = " + employee);
    }
}
3.3.2.7 注入属性-级联赋值
  • Dept.java
package top.open1024.spring;

import java.io.Serializable;

/**
 * 部门
 */
public class Dept implements Serializable {

    /**
     * 部门名称
     */
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Dept{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • Employee.java
package top.open1024.spring;

import java.io.Serializable;

/**
 * 员工
 */
public class Employee implements Serializable {

    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String gender;

    /**
     * 一个员工属于一个部门
     */
    private Dept dept = new Dept();

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

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

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", dept=" + dept +
                '}';
    }
}
  • applicationContext.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: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="emp" class="top.open1024.spring.Employee">
        <property name="name" value="张三"/>
        <property name="gender" value="男"/>
        <property name="dept.name" value="测试部"/>
    </bean>
    
</beans>
  • 测试
package top.open1024.spring;

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

public class EmployeeTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Employee employee = context.getBean("emp", Employee.class);
        System.out.println("employee = " + employee);
    }
}
3.3.2.8 注入集合类型属性

注入数组类型属性、注入List类型属性、注入Set类型属性、注入Map类型属性

  • Student.java
package top.open1024.spring;

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

public class Student {

    private String[] courses;

    private List<String> list;

    private Map<String, String> map;

    private Set<String> set;

    public String[] getCourses() {
        return courses;
    }

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

    public List<String> getList() {
        return list;
    }

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

    public Map<String, String> getMap() {
        return map;
    }

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

    public Set<String> getSet() {
        return set;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "courses=" + Arrays.toString(courses) +
                ", list=" + list +
                ", map=" + map +
                ", set=" + set +
                '}';
    }
}
  • applicationContext.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: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="top.open1024.spring.Student">
        <property name="courses">
            <array>
                <value>Java课程</value>
                <value>Linux课程</value>
                <value>前端课程</value>
            </array>
        </property>
        <property name="list">
            <list>
                <value>list1</value>
                <value>list2</value>
                <value>list3</value>
            </list>
        </property>
        <property name="set">
            <set>
                <value>set1</value>
                <value>set2</value>
                <value>set3</value>
            </set>
        </property>
        <property name="map">
            <map>
                <entry key="map-key1" value="map-value1"/>
                <entry key="map-key2" value="map-value2"/>
                <entry key="map-key2" value="map-value2"/>
            </map>
        </property>

    </bean>

</beans>
  • 测试
package top.open1024.spring;

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

public class StudentTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        Student student = context.getBean("student", Student.class);

        System.out.println("student = " + student);
    }
}
3.3.2.9 注入集合对象类型
  • Course.java
package top.open1024.spring;

public class Course {

    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Course{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • Student.java
package top.open1024.spring;

import java.util.List;

public class Student {

    private List<Course> courseList ;

    public List<Course> getCourseList() {
        return courseList;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "courseList=" + courseList +
                '}';
    }
}
  • applicationContext.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: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="top.open1024.spring.Student">
        <property name="courseList">
            <list>
                <ref bean="java"></ref>
                <ref bean="php"></ref>
            </list>
        </property>
    </bean>

    <bean id="java" class="top.open1024.spring.Course">
        <property name="name" value="java"/>
    </bean>

    <bean id="php" class="top.open1024.spring.Course">
        <property name="name" value="php"/>
    </bean>

</beans>
  • 测试
package top.open1024.spring;

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

public class StudentTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        Student student = context.getBean("student", Student.class);

        System.out.println("student = " + student);
    }
}
3.3.2.10 工厂Bean

工厂Bean的步骤:

  • ①创建类,让这个类作为工厂Bean,实现接口FactoryBean。
  • ②实现接口里面的方法,在方法的定义中定义返回的Bean类型。
  • Demo.java
package top.open1024.spring;

public class Demo {

    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Demo{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • FactoryBeanDemo.java
package top.open1024.spring;

import org.springframework.beans.factory.FactoryBean;

public class FactoryBeanDemo implements FactoryBean<Demo> {

    /**
     * 定义返回Bean
     *
     * @return
     * @throws Exception
     */
    @Override
    public Demo getObject() throws Exception {
        Demo demo = new Demo();
        demo.setName("这是一个Demo");
        return demo;
    }

    @Override
    public Class<?> getObjectType() {
        return Demo.class;
    }

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

  • applicationContext.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: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="demo" class="top.open1024.spring.FactoryBeanDemo"></bean>
    
</beans>
  • 测试
package top.open1024.spring;

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

public class DemoTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        Demo demo = context.getBean("demo", Demo.class);

        System.out.println("demo = " + demo);
    }
}
3.3.3 Bean的作用域
3.3.3.1 概述
  • 在Spring中,可以设置创建Bean实例是单实例还是多实例。
  • 在Spring中,默认情况下,Bean是单实例对象。
3.3.3.2 单实例Bean
  • Book.java
package top.open1024.spring;

public class Book {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • applicationContext.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: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="book" class="top.open1024.spring.Book"></bean>

</beans>
  • 测试
package top.open1024.spring;

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

public class BookTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        Book book2 = context.getBean("book", Book.class);

        System.out.println(book == book2);//true

    }
}
3.3.3.3 多实例Bean
  • Book.java
package top.open1024.spring;

public class Book {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • applicationContext.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
     <!--
            默认情况下,scope的值是singleton,表示单实例Bean。
            如果scope的值是prototype,则表示多实例Bean。
     --> 
     <bean id="book" class="top.open1024.spring.Book" scope="prototype"></bean>

</beans>
  • 测试
package top.open1024.spring;

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

public class BookTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        Book book2 = context.getBean("book", Book.class);

        System.out.println(book == book2);//false
    }
}
3.3.3.4 总结

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

3.3.4 Bean的生命周期
3.3.4.1 概述
  • 生命周期:从对象的创建到对象的销毁的过程。
  • Bean生命周期:
    • ①通过构造器创建Bean实例(默认是通过无参构造器)
    • ②为Bean的属性设置值和对其他Bean的引用(调用Setter方法)
  • 调用Bean的初始化的方法(需要进行配置初始化的方法)。
    • ④使用Bean对象。
    • ⑤当容器的关闭的时候,会调用Bean的销毁方法(需要进行配置销毁的方法)。
3.3.4.2 应用示例
  • Book.java
package top.open1024.spring;

public class Book {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("②调用setter方法设置属性值");
        this.name = name;
    }

    public Book() {
        System.out.println("①无参构造方法");
    }

    public void init() {
        System.out.println("③这是初始化方法...");
    }

    public void destroy() {
        System.out.println("⑤这是销毁的方法...");
    }


    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • applicationContext.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
     <!--
            init-method配置初始化方法
            destroy-method配置销毁方法
     -->
     <bean id="book" class="top.open1024.spring.Book" init-method="init" destroy-method="destroy">
          <property name="name" value="哈哈"/>
     </bean>

</beans>
  • 测试:
package top.open1024.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //④调用Bean对象
        Book book = context.getBean("book", Book.class);
        System.out.println("④调用Bean对象" + book);
        //手动调用让容器关闭
        context.close();

    }
}
3.3.4.3 后置处理器
  • 后置处理器:会在Bean的初始化前后处理,将Bean传递给Bean的后置处理器方法

  • 添加后置处理器的Bean的生命周期:

    • ①通过构造器创建Bean实例(默认是通过无参构造器)
    • ②为Bean的属性设置值和对其他Bean的引用(调用Setter方法)
    • ③将Bean实例传递给Bean的后置处理器的方法。
    • ④调用Bean的初始化的方法(需要进行配置初始化的方法)。
    • ⑤将Bean实例传递给Bean的后置处理器的方法。
    • ⑥使用Bean对象。
    • ⑦当容器的关闭的时候,会调用Bean的销毁方法(需要进行配置销毁的方法)。
  • 示例:只需要让类实现BeanPostProcessor,并重写其中的方法即可。

  • Book.java

package top.open1024.spring;

public class Book  {

    public void init(){
        System.out.println("Book初始化...");
    }
}
  • Demo.java
package top.open1024.spring;

public class Demo {

    public void init(){
        System.out.println("Demo初始化...");
    }
}
  • MyBeanPostProcessor.java
package top.open1024.spring;

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;
    }
}
  • applicationContext.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: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="book" class="top.open1024.spring.Book" init-method="init" ></bean>

     <bean id="demo" class="top.open1024.spring.Demo" init-method="init"></bean>

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

</beans>
  • 测试:
package top.open1024.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    }
}
3.3.5 自动装配
3.5.5.1 概述
  • 根据指定装配规则(属性名称或属性类型),Spring自动将匹配的属性值进行注入。
3.5.5.2 应用示例
  • 示例:根据属性名称自动注入
package top.open1024.spring;

import java.io.Serializable;

public class Dept implements Serializable {

    @Override
    public String toString() {
        return "Dept{}";
    }
}
  • Employee.java
package top.open1024.spring;

import java.io.Serializable;

public class Employee implements Serializable {

    private Dept dept;

    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "dept=" + dept +
                '}';
    }
}
  • applicationContext.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: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="dept" class="top.open1024.spring.Dept"></bean>

     <!--
          实现自动装配
          bean标签中有属性autowire:
               - 属性值 byName,根据属性名注入,注入Bean的id值要和类属性一致
               - 属性值 byType,根据属性类型注入,注入Bean的类型要和类属性类型一致
     -->
     <bean id="emp" class="top.open1024.spring.Employee" autowire="byName"></bean>

</beans>
  • 测试:
package top.open1024.spring;

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

public class EmployeeTest {
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Employee employee = context.getBean("emp",Employee.class);

        System.out.println("employee = " + employee);
    }
}

3.3.6 外部属性文件
  • 示例:通过引入外部属性文件配置数据库连接池
  • 导入数据库连接池的Maven坐标
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>

  • db.properties
jdbc.url=jdgc:mysql://localhost:3306/db01
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc,password=123456
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

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

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

</beans>

3.4 基于注解方式进行Bean管理的操作

3.4.1 什么是注解?
  • 注解是代码的一种特殊标记,注解可以作用在类、方法和属性上面。
  • 语法:
@注解名称(属性名称=属性值,属性名称=属性值...)
  • 使用注解的目的,是简化XML的配置。
3.4.2 Spring针对Bean管理中创建对象提供的注解
  • @Component
  • @Service
  • @Controller
  • @Repository

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

3.4.3 基于注解方式创建对象

• 示例:
• UserService.java

package top.open1024.spring.service;

import org.springframework.stereotype.Service;

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

    public void add() {
        System.out.println("UserService  ...");
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--
        开启组件扫描
            如果扫描多个包,多个包之间使用,隔开
            如果扫描多个包,可以使用扫描包的是上层目录
    -->
    <context:component-scan base-package="top.open1024.spring"></context:component-scan>

</beans>
  • 测试:
package top.open1024.spring;

import top.open1024.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}
3.4.4 基于注解注入属性
3.4.4.1 概述
  • Spring注入属性提供的注解:

    • @Autowired:根据属性类型进行自动装配。
    • @Qualifier:根据属性名称进入注入。
    • @Resource:可以根据类型注入,也可以根据名称注入。
    • @Value:注入普通类型属性
3.4.4.2 @Autowired注解的使用
  • 示例:
  • UserDao.java
package top.open1024.spring.dao;
public interface UserDao {
    void add();
}
  • UserDaoImpl.java
package top.open1024.spring.dao.impl;

import top.open1024.spring.dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("UserDaoImpl。。。add。。。");
    }
}
  • UserService.java
package top.open1024.spring.service;

public interface UserService {

    void add();

}
  • UserServiceImpl.java
package top.open1024.spring.service.impl;

import top.open1024.spring.dao.UserDao;
import top.open1024.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    //@Autowired按照类型注入
    @Autowired
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("UserServiceImpl...add...");
        userDao.add();
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="top.open1024.spring"></context:component-scan>

</beans>
  • 测试:
package top.open1024.spring;

import top.open1024.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Spring5Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.add();
    }

}
3.4.4.3 @Qualifier注解的使用
  • UserDao.java
package top.open1024.spring.dao;

public interface UserDao {

    void add();

}
  • UserDaoImpl.java
package top.open1024.spring.dao.impl;

import top.open1024.spring.dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("UserDaoImpl。。。add。。。");
    }
}
  • UserService.java
package top.open1024.spring.service;

public interface UserService {

    void add();

}
  • UserServiceImpl.java
package top.open1024.spring.service.impl;

import top.open1024.spring.dao.UserDao;
import top.open1024.spring.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    //@Qualifier注解按照属性名称注入,其中属性value的值是要注入Bean的id
    //@Qualifier注解要和@Autowired配合使用
    @Autowired
    @Qualifier(value = "userDaoImpl")
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("UserServiceImpl...add...");
        userDao.add();
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="top.open1024.spring"></context:component-scan>

</beans>
  • 测试:
package top.open1024.spring;

import top.open1024.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Spring5Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.add();
    }

}
3.4.4.4 @Resource注解的使用
  • UserDao.java
package top.open1024.spring.dao;

public interface UserDao {

    void add();

}
  • UserDaoImpl.java
package top.open1024.spring.dao.impl;

import top.open1024.spring.dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("UserDaoImpl。。。add。。。");
    }
}
  • UserService.java
package top.open1024.spring.service;

public interface UserService {
    void add();
}
  • UserServiceImpl.java
package top.open1024.spring.service.impl;

import top.open1024.spring.dao.UserDao;
import top.open1024.spring.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    //@Resource注解如果不写name属性,那么就是按照类型注入
    //@Resource注解如果写name属性,那么就是按照名称注入
    @Resource(name = "userDaoImpl")
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("UserServiceImpl...add...");
        userDao.add();
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <context:component-scan base-package="top.open1024.spring"></context:component-scan>

</beans>
  • 测试:
package top.open1024.spring;

import top.open1024.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Spring5Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.add();
    }

}
3.4.5 完全注解开发
3.4.5.1 开发步骤
  • ①创建一个配置类,用来替代applicationContext.xml文件。

  • ②测试的时候,使用的是AnnotationConfigApplicationContext,而不是ClassPathXmlApplicationContext。

3.4.5.2 应用示例
  • UserDao.java
package top.open1024.spring.dao;
public interface UserDao {
    void add();
}
  • UserDaoImpl.java
package top.open1024.spring.dao.impl;

import top.open1024.spring.dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("UserDaoImpl。。。add。。。");
    }
}
  • UserService.java
package top.open1024.spring.service;

public interface UserService {

    void add();

}
  • UserServiceImpl.java
package top.open1024.spring.service.impl;

import top.open1024.spring.dao.UserDao;
import top.open1024.spring.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    //@Resource注解如果不写name属性,那么就是按照类型注入
    //@Resource注解如果写name属性,那么就是按照名称注入
    @Resource(name = "userDaoImpl")
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("UserServiceImpl...add...");
        userDao.add();
    }
}
  • SpringConfing.java
package top.open1024.spring.config;

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

/**
 * 配置类,相当于applicationContext.xml
 */
@Configuration
@ComponentScan(basePackages = "top.open1024.spring")
public class SpringConfig {

}
  • 测试:
package top.open1024.spring;

import top.open1024.spring.config.SpringConfig;
import top.open1024.spring.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Spring5Test {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.add();
    }

}
0

评论区