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

Spring入门宝典(一)Spring介绍 & SpringIOC(上)

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

Spring入门宝典(一)Spring介绍 & SpringIOC(上)

目录

一.Spring介绍

1.Spring简介

2.Spring体系结构

二.SpringIOC(上)

1.控制反转思想

2.自定义对象容器

3. Spring实现IOC

4.Spring容器类型

5.对象的创建方式 

(1)使用构造方法

(2)使用工厂类的方法

(3)使用工厂类的静态方法


一.Spring介绍

1.Spring简介 Spring 是一个开源框架,为简化企业级开发而生。它以 IOC (控制反转)和 AOP (面向切面)为思想内核,提供了控制层 SpringMVC 、数据层 SpringData 、服务层事务管理等众多技术,并 可以整合众多第三方框架。 Spring 将很多复杂的代码变得优雅简洁,有效的降低代码的耦合度,极大的方便项目的后期维护、升级和扩展。 Spring 官网地址: https://spring.io/  

2.Spring体系结构

Spring 框架根据不同的功能被划分成了多个模块,这些模块可以满足一切企业级应用开发的需求,在开发过程中可以根据需求有选择 性地使用所需要的模块。
  • Core Container:Spring核心模块,任何功能的使用都离不开该模块,是其他模块建立的基础。
  • Data Access/Integration:该模块提供了数据持久化的相应功能。
  • Web:该模块提供了web开发的相应功能。
  • AOP:提供了面向切面编程实现
  • Aspects:提供与AspectJ框架的集成,该框架是一个面向切面编程框架。
  • Instrumentation:提供了类工具的支持和类加载器的实现,可以在特定的应用服务器中使用。
  • Messaging:为Spring框架集成一些基础的报文传送应用
  • Test:提供与测试框架的集成

 任何功能的使用都离不开Spring核心模块。

二.SpringIOC(上)

1.控制反转思想 IOC(Inversion of Control) :程序将创建对象的权利交给框架。 之前在开发过程中,对象实例的创建是由调用者管理的,代码如下:
public interface StudentDao {
   // 根据id查询学生
   Student findById(int id);
}

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

public class StudentService {
    public Student findStudentById(int id){
        // 此处就是调用者在创建对象
        StudentDao studentDao = new StudentDaoImpl();
        return studentDao.findById(1);
    }
}
这种写法有两个缺点:
  1. 浪费资源:StudentService调用方法时即会创建一个对象,如果不断调用方法则会创建大量StudentDao对象,会造成内存浪费。
  2. 代码耦合度高:假设随着开发,我们创建了StudentDao另一个更加完善的实现类StudentDaoImpl2,如果在StudentService中想使用StudentDaoImpl2,则必须修改源码。
而 IOC 思想是将创建对象的权利交给框架,框架会帮助我们创建对象,分配对象的使用,控制权由程序代码转移到了框架中,控制权 发生了反转,这就是 Spring 的 IOC 思想。而 IOC 思想可以完美的解决 以上两个问题。

2.自定义对象容器

接下来我们通过一段代码 模拟IOC思想 。创建一个集合容器,先将对象创建出来放到容器中,需要使用对象时,只需要从容器中获取 对象即可,而不需要重新创建,此时容器就是对象的管理者。

首先创建一个空项目

然后在此空项目下创建一个普通的 java项目(子模块)

然后在此子模块下创建包com.first.domain,然后在domain下创建实体类Student

(1)创建实体类

public class Student {
    private int id;
    private String name;
    private String address;
 // 省略getter/setter/构造方法/tostring
}

(2)创建Dao接口和实现类

创建接口StudentDao,路径为com/first/dao

package com.first.dao;

import com.first.domain.Student;

public interface StudentDao {
    //根据id查询学生
    Student findById(int id);
}

然后仍在此包下创建实现类StudentDaoImpl

package com.first.dao;

import com.first.domain.Student;

public class StudentDaoImpl implements StudentDao{
    @Override
    public Student findById(int id) {
        //这里直接返回一个学生对象,模拟从数据库查询
        return new Student(1,"断线","北京");
    }
}

再在此包下创建实现类StudentDaoImpl2,看这两个实现类能否自由切换

package com.first.dao;

import com.first.domain.Student;

public class StudentDaoImpl2 implements StudentDao{
    @Override
    public Student findById(int id) {
        System.out.println("新方法!!!");
        //这里直接返回一个学生对象,模拟从数据库查询
        return new Student(1,"断线","北京");
    }
}

在com/first/下新建一个service,然后在service下新建一个StudentService

传统方法是像下面一样new一个对象来调用dao层的接口函数

package com.first.service;

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

public class StudentService {
    public Student findStudentById(int id){
        //传统方法是像下面一样new一个对象来调用dao层的接口函数
        StudentDaoImpl studentDao = new StudentDaoImpl();
        return studentDao.findById(id);
    }
}

(3)创建配置文件bean.properties,该文件中定义管理的对象

为了解决上面这个问题,在src下新建一个bean.properties

 内容为:左边为对象名,右边是类

studentDao=com.first.dao.StudentDaoImpl

(4)创建容器管理类,该类在类加载时读取配置文件,将配置文件中 配置的对象全部创建并放入容器中。

在first下创建Container类

package com.first;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class Container {
    static Map map = new HashMap();
    static {
        // 读取配置文件
        InputStream is = Container.class.getClassLoader().getResourceAsStream("bean.properties");
        Properties properties = new Properties();
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 遍历配置文件的所有配置
        Enumeration keys = properties.keys();
        while (keys.hasMoreElements()){
            String key = keys.nextElement().toString();
            String value = properties.getProperty(key);
            try {
                // 创建对象
                Object o = Class.forName(value).newInstance();
                // 将对象放入集合中
                map.put(key,o);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//static

    // 从容器中获取对象
    public static Object getBean(String key){
        return map.get(key);
    }
}
 

(5)创建Dao对象的调用者StudentService

修改StudentService.java

package com.first.service;

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

public class StudentService {
    public Student findStudentById(int id){
        //传统方法是像下面一样new一个对象来调用dao层的接口函数
        //StudentDaoImpl studentDao = new StudentDaoImpl();
        //从对象容器中获取
        StudentDao studentDao = (StudentDao) Container.getBean("studentDao");
        System.out.println(studentDao.hashCode());
        return studentDao.findById(id);
    }
}

(6)测试StudentService

在first下新建测试类Test

package com.first;

import com.first.service.StudentService;

public class Test {
    //快捷方式:psvm
    public static void main(String[] args) {
        //studentService对象也可以放到容器中创建,这里不再演示
        StudentService studentService = new StudentService();
        System.out.println(studentService.findStudentById(1));
        System.out.println(studentService.findStudentById(1));
    }
}

输出:

1846274136
Student{id=1, name='断线', address='北京'}
1846274136
Student{id=1, name='断线', address='北京'}

可以看见两次调用函数输出的hasCode值一样,说明是一个对象,即从容器中拿到的同一个对象,节约了资源!

又如果想调用实现类StudentDaoImpl2的函数,那么只要把配置文件bean.properties中的StudentDaoImpl改成StudentDaoImpl2即可,这样无需修改源码,也就是不用重新编译,另外这里把StudentService也让容器生成,

那么bean.properties:

studentDao=com.first.dao.StudentDaoImpl2
studentService=com.first.service.StudentService

Test.java:

package com.first;

import com.first.service.StudentService;

public class Test {
    //快捷方式:psvm
    public static void main(String[] args) {
        StudentService studentService = (StudentService) Container.getBean("studentService");
        System.out.println(studentService.findStudentById(1));
        System.out.println(studentService.findStudentById(1));
    }
}

输出:

1846274136
新方法!!!
Student{id=1, name='断线', address='北京'}
1846274136
新方法!!!
Student{id=1, name='断线', address='北京'}

以上就是Spring的IOC思想,Spring自己就自带容器!

3. Spring实现IOC

接下来我们使用 Spring 实现 IOC , Spring 内部也有一个容器用来管理对象。

(1)创建Maven工程,引入依赖

在pom.xml中添加依赖:



    4.0.0

    com.first
    spring_IOC1
    1.0-SNAPSHOT

    
        
        
            org.springframework
            spring-context
            5.3.13
        
        
        
            junit
            junit
            4.12
            test
        
    

(2)创建POJO类、Dao类和接口

创建目录与文件如下:

dao包和domain包下的那几个文件从上节的工程复制过来就行。

(3)编写xml配置文件,配置文件中配置需要Spring帮我们创建的对象。

上节的配置文件是写在properties文件中,而spring是写在xml文件中。

在resources下建bean.xml,内容如下:



    
    

(4)测试从Spring容器中获取对象。

在test/java下创建com/first/,然后在此之下创建TestContainer.java

package com.first;

import com.first.dao.StudentDao;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestContainer {
    @Test
    public void t1(){
        //创建Spring对象
        ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //从容器获取对象
        StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao");
        StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao");
        System.out.println(studentDao1.hashCode());
        System.out.println(studentDao2.hashCode());
        System.out.println(studentDao1.findById(1));
    }
}

输出:

455538610
455538610
Student{id=1, name='断线', address='北京'}

可以看到hasCode值一样,所以这两个是同一个对象。

如果想调用StudentDaoImpl2的实现函数,那么只需在bean.xml中修改class项即可,

输出:

455538610
455538610
新方法!!!
Student{id=1, name='断线', address='北京'}

4.Spring容器类型 容器接口
  • BeanFactory:BeanFactory是Spring容器中的顶层接口,它可以对Bean对象进行管理。 但是这个接口用的不多。
  • ApplicationContext:ApplicationContext是BeanFactory的子接口。它除了继承 BeanFactory的所有功能外,还添加了对国际化、资源访问、事件传播等方面的良好支持。
ApplicationContext 有以下三个常用实现类: 容器实现类
  • ClassPathXmlApplicationContext:该类可以从项目中读取配置文件,参数是在项目中的相对路径,比如上节写的 "bean.xml"就是相对于项目根路径写的,所以可以知道 java和resources文件都是根,因为maven文件创建时已经帮我们设置为根了,联想到maven系列篇章中的Mark Directory as
    //创建Spring对象
    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  • FileSystemXmlApplicationContext:该类从磁盘中读取配置文件,参数是配置文件在硬盘里的绝对路径。
  • AnnotationConfigApplicationContext:使用该类不读取配置文件,而是会读取注解

5.对象的创建方式 

Spring 会帮助我们创建 bean ,那么它底层是调用什么方法进行创建的呢?

(1)使用构造方法 Spring 默认使用类的 空参 构造方法创建 bean :
// 假如类没有空参构造方法,将无法完成bean的创建
public class StudentDaoImpl implements
StudentDao{
    public StudentDaoImpl(int a){}
    
    @Override
    public Student findById(int id) {
        // 模拟根据id查询学生
        return new Student(1,"百战程序员","北 京");
   }
}

再次调用测试函数时会报错,因为类如果定义了有参的构造方法,那么它就不会自动生成无参的构造方法,所以会报错。

(2)使用工厂类的方法 Spring 可以调用工厂类的方法创建 bean : (1)创建工厂类,工厂类提供创建对象的方法: 测试这个方法一些添加的测试条件(为了方便演示):

在dao包下创建StudentDaoFactory类(工厂类),

package com.first.dao;

public class StudentDaoFactory {
    public StudentDao getStudentDao(){
        
        return new StudentDaoImpl(1);
    }
}
(2)在配置文件中配置创建 bean 的方式为工厂方式。


    

    
    
    
    
    

(3) 测试 仍用之前的测试函数测试,可见此方法可以!输出如下:
1693847660
1693847660
Student{id=1, name='断线', address='北京'}

(3)使用工厂类的静态方法 Spring 可以调用工厂类的静态方法创建 bean : (1) 创建工厂类,工厂提供创建对象的静态方法。 在dao包下创建StudentDaoFactory2类
package com.first.dao;

public class StudentDaoFactory2 {
    public static StudentDao getStudentDao(){
        
        return new StudentDaoImpl(1);
    }
}
使用静态类可以直接用类名调用函数,而不用再用创建工厂对象! (2)在配置文件中配置创建 bean 的方式为工厂静态方法。


    
    


    
    

    


    
    
 
(3)测试 仍用之前的测试函数测试,可见此方法可以!输出如下:  
2092769598
2092769598
Student{id=1, name='断线', address='北京'}

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

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

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