0


Spring之IOC

2.1、IOC本质控制反转

IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现Ioc的一种方法,也有人认为DI只是oC的另一种说法。没有引oC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。

采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。

控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在spring中实现控制反转的是IoC容器,其实现方法是依赖注入(Dependency Injection,Dl)。

2.2、Spring入门案例

UserServiceImpl:

publicclassUserServiceImplimplementsUserService{publicvoidsave(){System.out.println("user service running ..............");}}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd"><!--1.创建spring控制的资源--><beanid="userService"class="com.lfs.service.Impl.UserServiceImpl"/></beans>

测试:

publicclassUserApp{//这是一个main方法,是程序的入口:publicstaticvoidmain(String[] args){//2加载配置文件ApplicationContext ctx =newClassPathXmlApplicationContext("applicationContext.xml");UserService bean =(UserService) ctx.getBean("userService");
        bean.save();}}

结果:

在这里插入图片描述

3.1、别名

在这里插入图片描述

3.2、Bean的配置

id : bean 的唯一标识符,也就是相当于我们学的对象名

class :bean 对象所对应的全限定名 :包名+类

name :也是别名,而且name可以同时取多个别名

scope:定义bean的作用范围

scope属性:

在这里插入图片描述

singleton属性值:单例----创建的对象是同一个对象。未使用就会创建对象

prototype属性值:非单列----创建的对象不是同一个对象。使用了才会创建对象

Bean生命周期

在这里插入图片描述

需要执行ctx.close();就会执行destroy方法

<!--scope用于控制bean创建后的对象是否是单列-->
<bean id="userService3" scope="singleton" class="com.lfs.service.Impl.UserServiceImpl"/>

<!--init-method与destroy-method用于bean的生命周期-->
<bean id="userService3" scope="prototype" init-method="init" destroy-method="destroy" class="com.lfs.service.Impl.UserServiceImpl"/>

bean对象的创建方式

在这里插入图片描述

<!--静态工厂创建bean-->
    <bean id="userService4" class="com.lfs.service.UserServiceFactory" factory-method="getService"/>

    <!--实例创建工厂bean,依赖工厂对象对应的bean-->
    <bean id="factoryBean" class="com.lfs.service.UserServiceFactory2"/>
    <bean id="userService5" factory-bean="factoryBean" factory-method="getService"/>

5.3、import

在这里插入图片描述

在这里插入图片描述

这个import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个

标签: spring java 后端

本文转载自: https://blog.csdn.net/qq_64071654/article/details/127234100
版权归原作者 楠慧 所有, 如有侵权,请联系我们删除。

“Spring之IOC”的评论:

还没有评论