Spring框架IOC容器和DI依赖注入

目录

  • Spring框架IOC容器和DI依赖注入
    • 介绍
    • 入门案例
      • pom.xml依赖引入
      • BookDao
      • BookDaoImpl
      • BookService
      • BookServiceImpl
      • applicationContext.xml
      • 测试类
    • Bean实例化
      • 静态工厂实例化
        • OrderDao
        • OrderDaoImpl
        • OrderDaoFactory
        • applicatoinContext.xml
        • 测试类
      • 实例工厂实例化
        • UserDao
        • UserDaoImpl
        • UserDaoFactory
        • applicationContext.xml
        • 测试类
      • 使用实例工厂实现FactoryBean接口实例化
        • UserDaoFactoryBean
        • applicationContext.xml
        • 测试类
    • Bean的生命周期
      • BrandService
      • BrandServiceImpl
      • BrandDao
      • BrandDaoImpl
      • applicatonContext.xml
      • 测试类
    • 其他类型依赖注入
      • applicationContext.xml

Spring框架IOC容器和DI依赖注入

介绍

IOC(Invertion Of Control):控制反转,使用对象时,由使用new创建对象转变为由外部提供对象,此过程中对象的创建控制权由程序转移到外部的思想称之为控制反转.

DI(Dependency Injection):依赖注入,在容器中建立bean与bean之间的关系的过程,称之为依赖注入

入门案例

pom.xml依赖引入


<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.0modelVersion>

    <groupId>com.shifangroupId>
    <artifactId>spring-01-ioc-di-beanartifactId>
    <version>1.0-SNAPSHOTversion>

    <properties>
        <maven.compiler.source>11maven.compiler.source>
        <maven.compiler.target>11maven.compiler.target>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.2.10.RELEASEversion>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.1version>
        dependency>
    dependencies>

project>

BookDao

public interface BookDao {
    void save();
}

BookDaoImpl

public class BookDaoImpl implements BookDao {

    @Override
    public void save() {
        System.out.println("BookDao save...");
    }
}

BookService

public interface BookService {
    void save();
}

BookServiceImpl

public class BookServiceImpl implements BookService {

    private BookDao bookDao;

    //给spring容器注入提供set方法
    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    @Override
    public void save() {
        bookDao.save();
    }
}

applicationContext.xml


<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="bookDaoImpl" class="com.shifan.dao.impl.BookDaoImpl" name="bookDao"/>
    
    
    <bean id="bookServiceImpl" class="com.shifan.service.impl.BookServiceImpl" autowire="byType">
        <property name="bookDao" ref="bookDaoImpl"/>
    bean>
beans>

测试类

    //获取spring容器
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    @Test
    public void testGetBean(){
        //获取bean
/*        BookDao bookDao = (BookDao) applicationContext.getBean("bookDaoImpl");
        bookDao.save();*/
        BookService bookServiceImpl = (BookService) applicationContext.getBean("bookServiceImpl");
        bookServiceImpl.save();
    }

    @Test
    public void testBeanAlias(){
        //根据别名获取bean
        BookDao bookDao = (BookDao) applicationContext.getBean("bookDao");
        bookDao.save();
    }

Bean实例化

静态工厂实例化

OrderDao

public interface OrderDao {
    void order();
}

OrderDaoImpl

public class OrderDaoImpl implements OrderDao {
    @Override
    public void order() {
        System.out.println("ordering orders...");
    }
}

OrderDaoFactory

package com.shifan.factory;

import com.shifan.dao.OrderDao;
import com.shifan.dao.impl.OrderDaoImpl;

public class OrderDaoFactory {
    public static OrderDao getOrderDao(){
        System.out.println("order dao service options...");//模拟对象创建前的必要业务操作
        return new OrderDaoImpl();
    }
}

applicatoinContext.xml

    <!--
    静态工厂实例化(了解)
    指定静态工厂类全类名及其创建对象的方法
    -->
    <bean id="orderDao" class="com.shifan.factory.OrderDaoFactory" factory-method="getOrderDao"/>

测试类

@Test
public void testStaticFactory(){
    //获取通过静态工厂创建的对象
    OrderDao orderDao = (OrderDao) applicationContext.getBean("orderDao");
    orderDao.order();
}

实例工厂实例化

UserDao

public interface UserDao {
    void save();
}

UserDaoImpl

public class UserDaoImpl implements UserDao {
    @Override
    public void save() {
        System.out.println("user dao save...");
    }
}

UserDaoFactory

public class UserDaoFactory {
    public UserDao getUserDao(){
        System.out.println("user dao service options...");//模拟对象创建前的必要业务操作
        return new UserDaoImpl();
    }
}

applicationContext.xml

    
    <bean id="userDaoFactory" class="com.shifan.factory.UserDaoFactory"/>
    <bean id="userDao" factory-method="getUserDao" factory-bean="userDaoFactory"/>

测试类

    @Test
    public void testInstanceFactory(){
        //获取通过实例工厂bean创建的对象
        UserDao userDao = (UserDao) applicationContext.getBean("userDao");
        userDao.save();
    }

使用实例工厂实现FactoryBean接口实例化

UserDaoFactoryBean

/**
 * 使用FactoryBean简化实例工厂方式实例化bean
 * FactoryBean还有一个方法boolean isSingleton()
 * 用于设置是否为单例,不重写则默认返回true,表示是单例
 */
public class UserDaoFactoryBean implements FactoryBean<UserDao> {
    /**
     * 被重写后,在方法中进行对象的创建并返回
     * @return
     * @throws Exception
     */
    @Override
    public UserDao getObject() throws Exception {
        return new UserDaoImpl();
    }

    /**
     * 被重写后,主要返回的是被创建类的Class对象
     * @return
     */
    @Override
    public Class<?> getObjectType() {
        return UserDao.class;
    }

}

applicationContext.xml

    
    <bean id="userDaoFactoryBean" class="com.shifan.factory.UserDaoFactoryBean"/>

测试类

    //使用FactoryBean简化
    @Test
    public void testFactoryBean(){
        UserDao userDao = (UserDao) applicationContext.getBean("userDaoFactoryBean");
        userDao.save();
    }

Bean的生命周期

BrandService

public interface BrandService {
    void save();
}

BrandServiceImpl

/**
 实现InitializingBean和DisposableBean接口,重写方法,简化初始化方法和销毁方法的编写与配置,实现bean生命周期控制(了解)
 */
public class BrandServiceImpl implements BrandService , InitializingBean, DisposableBean {

    private BrandDao brandDao;

    //使用构造器注入brandDao
    public BrandServiceImpl(BrandDao brandDao){
        this.brandDao = brandDao;
    }
    //使用set方法注入brandDao
/*    public void setBrandDao(BrandDao brandDao) {
        System.out.println("set...");
        this.brandDao = brandDao;
    }*/

    @Override
    public void save() {
        brandDao.save();
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("release resource...");
    }

    /*
    afterPropertiesSet:属性设置后
    即brandDao被注入后才执行
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("initialize resource...");
    }
}

BrandDao

public interface BrandDao {
    void save();
}

BrandDaoImpl

public class BrandDaoImpl implements BrandDao {

    private String name;
    private int price;

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

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

    @Override
    public void save() {
        System.out.println("brand dao save..."+name+","+price);
    }
    //初始化方法
    public void init(){
        System.out.println("init resource...");
    }

    //销毁方法
    public void destroy(){
        System.out.println("rel resource...");
    }
}

applicatonContext.xml

	
    <bean id="brandDao" class="com.shifan.dao.impl.BrandDaoImpl" init-method="init" destroy-method="destroy">
        
        <property name="name" value="飘柔"/>
        <property name="price" value="20"/>
    bean>

    <bean id="brandService" class="com.shifan.service.impl.BrandServiceImpl">
        
        
        <constructor-arg name="brandDao" ref="brandDao"/>
    bean>

测试类

    @Test
    public void testBeanLifeCycle(){
/*        BrandDao brandDao = (BrandDao) applicationContext.getBean("brandDao");
        brandDao.save();*/
        BrandService brandService = (BrandService) applicationContext.getBean("brandService");
        brandService.save();
        /*
        调用ClassPathXmlApplicationContext类的close方法关闭容器
        避免IOC容器因为JVM退出而来不及销毁bean对象,导致销毁方法不执行
        ((ClassPathXmlApplicationContext)applicationContext).close();
         */

        /*
        注册钩子关闭容器
        在容器未关闭之前,设置回调函数,让JVM在退出之前回调此函数关闭容器
        与close方法相比:两种方法都能关闭容器,close方法是调用后就关闭容器,
        而registerShutdownHook方法是在JVM退出之前调用关闭容器
         */
        ((ClassPathXmlApplicationContext)applicationContext).registerShutdownHook();
    }

其他类型依赖注入

applicationContext.xml

    
    
    
    
    
    

你可能感兴趣的:(spring,java)