栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring入门宝典(二)SpringIOC (下) & 依赖注入DI (上)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring入门宝典(二)SpringIOC (下) & 依赖注入DI (上)

目录

一.SpringIOC(下)

1.对象的创建策略

2.对象的销毁时机

3.生命周期方法

4.获取Bean对象的方式

 二.依赖注入DI(上)

1.什么是依赖注入

2.依赖注入方式

(1)Setter注入

(2)构造方法注入

(3)自动注入


一.SpringIOC(下)

1.对象的创建策略

scope属性设置对象的创建第略。

Spring 通过配置 中的 scope 属性设置对象的创建策略,共有五种创建策略(前两种最常用):

singleton 

单例,默认策略。整个项目只会创建一个对象,通过 中的 lazy - init 属性可以设置单例对象的创建时机:
lazy-init="false"( 默认 ) :立即创建,在容器启动时会创建配置文件中的所有 Bean 对象。 lazy-init="true" :延迟创建,第一次使用 Bean 对象时才会创建。

配置单例策略:

修改实现类StudentDaoImpl2.java

在resources下创建bean.xml:



    
    
 
测试单例策略:
    //测试单例模式
    @Test
    public void t2(){
        //创建Spring对象,即容器启动,立即加载的话执行了下面一句代码就会创建对象
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml");
        System.out.println("---------------------------------------");
        //从容器获取对象,因为使用的是单例模式,所以下面三个hashCode都是一样的
        StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao");
        StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao");
        StudentDao studentDao3 = (StudentDao) ac.getBean("studentDao");
        System.out.println(studentDao1.hashCode());
        System.out.println(studentDao2.hashCode());
        System.out.println(studentDao3.hashCode());
    }

输出:

立即加载时

创建StudentDao!!!
---------------------------------------
1629911510
1629911510
1629911510

延时加载时

---------------------------------------
创建StudentDao!!!
292917034
292917034
292917034
prototype 多例, 每次 从容器中获取时都会创建对象。 这种方法有可能造成内存资源浪费。

测试:依旧是用函数 t2(),输出如下

---------------------------------------
创建StudentDao!!!
创建StudentDao!!!
创建StudentDao!!!
1629604310
142555199
1320677379
request 每次请求创建一个对象,只在 web 环境有效。 session 每次会话创建一个对象,只在 web 环境有效。 gloabal-session 一次集群环境的会话创建一个对象,只在 web 环境有效。

2.对象的销毁时机 对象的创建策略不同,销毁时机也不同:
  • singleton:对象随着容器的销毁而销毁。
  • prototype:使用JAVA垃圾回收机制销毁对象。
  • request:当处理请求结束,bean实例将被销毁。
  • session:当HTTP Session最终被废弃的时候,bean也会被销毁掉。
  • gloabal-session:集群环境下的session销毁,bean实例也将被销毁。

3.生命周期方法

init-method配置创建对象时执行的方法
destroy-method配置销毁对象时执行的方法

Bean 对象的生命周期包含创建 —— 使用 —— 销毁, Spring 可以配置Bean 对象在创建和销毁时自动执行的方法: (1)定义生命周期方法 在StudentDaoImpl2中定义两个 生命周期方法 (2)配置生命周期方法

    
(3)测试
//测试销毁时机
@Test
public void t3(){
    //创建Spring对象,即容器启动,立即加载的话执行了下面一句代码就会创建对象
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean1.xml");
    // 销毁Spring容器,ClassPathXmlApplicationContext才有销毁容器的方法
    ac.close();
}

输出:

输出了两个创建,一个是无参构造函数,一个是init-method配置的生命周期方法

创建StudentDao!!!
创建studentDao!!!
销毁studentDao!!!

4.获取Bean对象的方式 Spring 有多种获取容器中对象的方式: 通过 id/name 获取 即之前一直在使用的配置方式,把id换成name是等效的,但是这种方法在 获取对象时必须强制类型转换。 1 (1)配置文件
 

(2)获取对象

StudentDao studentDao = (StudentDao) ac.getBean("studentDao");
通过类型获取 1 (1)配置文件  
(2) 获取对象
StudentDao studentDao2 =ac.getBean(StudentDao.class);
可以看到使用类型获取不需要强转。但此种方法获取的对象必须是唯一的,即不能出现下面的情况:

这样两个对象类型相同,但是spring不知道获取哪个,所以会报错!

通过类型 +id/name 获取 虽然使用类型获取不需要强转,但如果在容器中有一个接口的多个实现类对象,则获取时会报错,此时需要使用类型 +id/name 获取。 (1)配置文件 name不一样,class也不一样

 
(2) 获取对象
StudentDao studentDao2 =ac.getBean("studentDao1",StudentDao.class);

 二.依赖注入DI(上)

1.什么是依赖注入

依赖注入是为对象的属性赋值。

依赖注入( Dependency Injection ,简称 DI ),它是 Spring 控制反转思想的具体实现。 控制反转将对象的创建交给了 Spring ,但是对象中可能会依赖其他 对象。比如 service 类中要有 dao 类的属性,我们称 service 依赖于 dao 。之前需要手动注入属性值,代码如下:
public interface StudentDao {
    Student findById(int id);
} 

public class StudentDaoImpl implements StudentDao{ 
    @Override
    public Student findById(int id) {
        // 模拟根据id查询学生
        return new Student(1,"百战程序员","北京");
    }
}

public class StudentService {
    //service依赖dao,手动注入属性值,即手动维护依赖关系
    private StudentDao studentDao = new StudentDaoImpl();
    public Student findStudentById(int id){
        return studentDao.findById(id);
   }
}
此时,当 StudentService 的想要使用 StudentDao 的另一个实现类如StudentDaoImpl2 时,则需要修改 Java 源码,造成代码的可维护性 降低。 而使用 Spring 框架后, Spring 管理 Service 对象与 Dao 对象,此时它能够为 Service 对象注入依赖的 Dao 属性值。这就是 Spring 的依赖注 入。 简单来说,控制反转是创建对象,依赖注入是为对象的属性赋 值。

2.依赖注入方式 在之前开发中,可以通过 setter 方法或构造方法设置对象属性值:
// setter方法设置属性
StudentService studentService = new StudentService();
StudentDao studentDao = new StudentDao();
studentService.setStudentDao(studentDao);

// 构造方法设置属性
StudentDao studentDao = new StudentDao();
StudentService studentService = new StudentService(studentDao);
Spring 可以通过调用 setter 方法或构造方法给属性赋值

右键空项目springdemo新建一个模块spring_DI

在pom.xml中引入如下依赖

    
        
        
            org.springframework
            spring-context
            5.3.13
        
        
        
            junit
            junit
            4.12
            test
        
    

像如下创建项目目录,相关文件从上个子模块中复制过来就行,

 bean.xml中清空内的内容,如下:




 

StudentService.java:

package com.first.service;

import com.first.dao.StudentDao;
import com.first.domain.Student;

public class StudentService {
    private StudentDao studentDao;
    public Student findStudentById(int id){
        return studentDao.findById(id);
    }
}

Spring可以通过调用setter方法或构造方法给属性赋值。

(1)Setter注入 1.被注入类编写属性的setter方法 在StudentService添加set方法,Generate生成就行
public void setStudentDao(StudentDao studentDao) {
    this.studentDao = studentDao;
}
2.配置文件中,给需要注入属性值的 中设置  



      
      
            
            
            
      

3.测试是否注入成功 在StudentService中添加get方法(还是generate)
package com.first;

import com.first.service.StudentService;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestContainer {
    @Test
    public void t1(){
        //创建Spring对象
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //从容器获取对象
        StudentService studentService = (StudentService) ac.getBean("studentService");
        System.out.println(studentService);
        System.out.println(studentService.getStudentDao());
        System.out.println(studentService.findStudentById(1));
    }
}

输出:

com.first.service.StudentService@4fb64261
com.first.dao.StudentDaoImpl@42607a4f
Student{id=1, name='断线', address='北京'}

可见依赖注入成功,这里的演示是把一个对象当作另一个类的一个属性,即从bean.xml中往被注入类注入。

(2)构造方法注入

1.被注入类编写有参的构造方法

在StudentService.java中添加

public StudentService(StudentDao studentDao) {
    this.studentDao = studentDao;
}

2.给需要注入属性值的 中设置




      
      
            
            

            
      

3.测试是否注入成功

还是上面那个测试方法。

(3)自动注入

自动注入是从容器中找到相应的对象设置为属性值。

自动注入不需要在 标签中添加其他标签注入属性值,而是自动从容器中找到相应的 bean 对象设置为属性值。 自动注入有两种配置方式:
  • 全局配置:在 中设置 default-autowire 属性可以定义所有bean对象的自动注入策略。
  • 局部配置:在 中设置 autowire 属性可以定义当前bean对象的自动注入策略。

 autowire的取值如下:

  • no:不会进行自动注入。
  • default:全局配置default相当于no,局部配置default表示使用全局配置
  • byName:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供set方法。
  • byType:在Spring容器中查找类型与属性类型相同的bean,并进行注入。需要提供set方法。
  • constructor:在Spring容器中查找id与属性名相同的bean,并进行注入。需要提供构造方法。

测试自动注入:  

(1)为依赖的对象提供setter和构造方法:

给StudentService.java添加setter和构造方法

(2)配置自动注入:




      
      









      

(3)测试

还是t1()函数,查看控制台输出如下

com.first.service.StudentService@43a0cee9
com.first.dao.StudentDaoImpl@eb21112
Student{id=1, name='断线', address='北京'}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/956413.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号