Spring IOC

一、主要内容

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w2Rc5d6b-1615990076730)(C:\Users\LEI\AppData\Roaming\Typora\typora-user-images\image-20210314150557079.png)]

二、Spring框架

2.1 Spring 框架概念

Spring 是一个开源的JavaEE的应用程序

主要核心是IOC(控制反转/依赖注入)和AOP(面向切面编程)两大技术

降低组件之间的耦合度,实现软件各层的解耦

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ypnh0Qig-1615990076733)(Spring IOC.assets/image-20210314153826635.png)]

2.2 Spring 源码架构

2.2.1 核心容器(Core Container)

包含模块spring-core, spring-beans, spring-context, spring-context-support,spring-expression.

spring-core 主要包含Spring框架基本的核心工具类
spring-beans 包含访问配置文件、创建和管理bean以及进行IoC/DI操作的相关类. BeanFactory
spring-context 构建与Core和Beans之上,继承了Beans的特性,扩展添加了国际化、时间传播、资源加载和对Context的创建和支持。ApplicationContext
spring-expression提供 一个强大的表达式语言用于在运行时查询和操作对象,该语言支持设置/获取属性值,属性的分配,方法的调用,访问数组上下文、容器和索引器、逻辑和算是运算符、命名变量以及从Spring的容器中根据名称检索对象
2.2.2 AOP和Instrumentation

包含模块spring-aop, spring-aspects, spring-instrument, spring-instrument-tomcat

spring-aop 提供了一个AOP联盟标准的面向方面编程的实现,它允许你定义方法拦截器与切入点,从而将逻辑代码与实现函数进行分离。
spring-aspects 提供了与AspectJ的集成
spring-instrument 提供了类工具的支持与classloader的实现,以便在特定的应用服务上使用。
spring-instrument-tomcat 包含了spring对于Tomcat的代理
2.2.3 消息(Messaging)

spring framework 4 包含了spring-messaging模块,其中使用了来自于spring integration项目的关键抽象,如Message, MessageChannel, MessageHandler等,他们可以作为基于消息的应用服务的基础。该模块还包含了一组可将消息映射到方法的注解,类似于spring-mvc的编程模型.

2.2.4 数据访问/集成(Data Access/ Integration)

包含spring-jdbc, spring-tx, spring-orm, spring-oxm, spring-jms.

spring-jdbc 提供了JDBC抽象层,消除了冗长的JDBC编码和解析数据库厂商特有的错误代码.
spring-tx 为实现了特定接口的类提供了可编程的声明式事务管理支持,对所有的POJOs都适用
spring-orm 提供了对象相关映射(ORM)集成,包含JPA, JDO, Hibernate,使用spring-orm模块可以将这些框架与spring提供的特性结合在一起使用,比如事务管理.
spring-oxm 提供了对Object/Xml Mapping实现的抽象,包括JAXB,Castor, XMLBeans, JiBX以及XStream.
spring-jms 包含了一些生产和消费消息的特性,从spring Framework 4.1开始,提供了与spring-messaging集成.
2.2.5 Web

包含spring-web, spring-webmvc, spring-websocket, spring-webmvc-portlet

spring-web提供了基于面向web集成的特性,如多文件上传功能、通过servlet listener初始化IoC容器与面向web的ApplicationContext,它还包含了HTTP客户端与Spring远程支持的web相关的部分.
spring-webmvc(又名web-servlet)包含了Spring对于Web应用的MVC与REST实现,Spring MVC框架提供了领域模型代码和Web表单之间的分离,并集成了Spring框架的所有其他特性.
spring-webmvc-portlet(又名web-portlet)提供了基于Portlet环境使用MVC的实现.

2.3 spring框架环境搭建

官方文档

https://docs.spring.io/spring-framework/docs/5.2.13.RELEASE/spring-framework-reference/core.html#beans-factory-metadata

	<!--添加Spring框架的核心依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.4.RELEASE</version>
    </dependency>

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        https://www.springframework.org/schema/beans/spring-beans.xsd">     
<bean id="..." class="...">         
*<!-- collaborators and configuration for this bean go here -->*    
</bean>     
<bean id="..." class="...">        
*<!-- collaborators and configuration for this bean go here -->*   
</bean>     
*<!-- more bean definitions go here -->* </beans>

定义Bean对象

​ id bean对象的唯一标识符

​ class bean对象(需要被实例化的bean对象)的全路径 包名+类名

在resources下创建spring.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userService" class="com.dl.service.UserService" />

</beans>

org.springframework.context.ApplicationContext接口代表Spring IoC容器,并负责实例化

2.4 实例化的两种方法
public static void main(String[] args) {
    BeanFactory factory = new ClassPathXmlApplicationContext("spring.xml");

    UserService userService = (UserService) factory.getBean("userService");
    userService.test();
}
public static void main(String[] args) {
    //org.springframework.context.ApplicationContext接口代表Spring IoC容器,并负责实例化
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
    //得到需要被实例化的对象
    UserService userService = (UserService) ac.getBean("userService");
    //调用方法
    userService.test();

}

三、Spring IOC容器Bean对象实例化模拟

3.1 定义Bean属性对象
3.2 添加dom4j坐标依赖
3.3 准备自定义配置文件
3.4 定义Bean工厂接口
3.5 定义Bean接口的实现类
3.6 测试自定义IOC容器

四、Spring IOC配置文件加载

Spring配置文件的加载

4.1 单个配置文件加载

1.通过相对路径加载

2.通过绝对路径加载配置文件

//相对路径
BeanFactory factory = new ClassPathXmlApplicationContext("spring.xml");
//绝对路径
BeanFactory factory1 = new FileSystemXmlApplicationContext("D:\\ClassFile\\Idea_File\\spring02\\src\\main\\resources\\spring.xml");


UserService userService = (UserService) factory.getBean("userService");
userService.test();
4.2 多个配置文件加载

1.可以通过可变参数设置多个配置文件

new ClassPathXmlApplicationContext("配置文件名""配置文件名")

2.设置一个总配置文件,在总配置文件中导入需要加载的配置文件

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--导入配置文件-->
    <import resource="spring.xml"/>
    <import resource="beans.xml"/>
</beans>

五、Spring IOC容器Bean对象实例化

5.1 构造器实例化

默认使用构造器实例化Bean对象,如果Bean对象未提供空构造,则实例化失败

5.2 静态工厂实例化
5.3 实例化工厂实例化

​ 定义工厂类,类中定义普通方法,方法返回实例化Bean对象

​ 1.先实例化工厂类

​ 2.定义Bean对象的bean标签,设置id属性值,指定对应工厂类及类中对应的方法

factory-bean 对应工厂类的bean标签id

factory-method 工厂类中的方法

<bean id="instanceService" class="com.dl.factory.InstanceFactory"/>
<bean id="accountService" factory-bean="instanceService" factory-method="createService"/>
BeanFactory factory = new ClassPathXmlApplicationContext("spring02.xml");

AccountService as = (AccountService) factory.getBean("accountService");
System.out.println(as);
public class InstanceFactory {
    /*定义普通方法,返回实例化bean对象*/
    public AccountService createService() {
        return new AccountService();
    }
}

六、Spring IOC注入

6.1 spring ioc 手动注入

6.1.1 set方法注入

需要属性字段提供set方法

通过property属性实现set方法注入

name 属性字段名称

ref 对应bean标签id属性值

value 具体值

<bean id="typeDao" class="com.dl.dao.TypeDao"></bean>
<bean id="typeService" class="com.dl.Service.TypeService">
    <!--set方法注入-->
    <property name="typeDao" ref="typeDao"/>
    <property name="port" value="8080"/>
</bean>
6.1.2 构造器注入

构造器注入

通过构造器的形参设置属性字段的值

通过construtor-arg标签实现构造器注入

name

value

index

<bean id="typeDao" class="com.dl.dao.TypeDao"></bean>
<bean id="typeService" class="com.dl.Service.TypeService">
    <constructor-arg name="typeDao" ref="typeDao" index="0" />
    <constructor-arg name="host" value="localhost"/>
    <constructor-arg name="port" value="8989"/>
</bean>
public TypeService(TypeDao typeDao, String host, Integer port) {
    this.typeDao = typeDao;
    this.host = host;
    this.port = port;
}

两个方法类分别调用各自的方法

错误
错误写法,出现了循环依赖问题,两个bean对象互相注入
解决方案:使用set注入
<bean id="resourceService" class="com.dl.Service.ResourceService">
    <!--构造器注入-->
    <constructor-arg name="testService" ref="testService"/>
</bean>
<bean id="testService" class="com.dl.Service.TestService">
    <constructor-arg name="resourceService" ref="resourceService"/>
</bean>
正解
正解
<bean id="resourceService" class="com.dl.Service.ResourceService">
    <!--set注入-->
   <property name="testService" ref="testService"/>
</bean>
<bean id="testService" class="com.dl.Service.TestService">
    <!--<constructor-arg name="resourceService" ref="resourceService"/>-->
    <property name="resourceService" ref="resourceService"/>
</bean>
6.1.3 注入方式 的选择

开发项目中set注入首选

6.1.4 p名称空间的使用

1.引入p命名空间

xmlns:p="http://www.springframework.org/schema/p"

2.在bean标签上使用p:属性字段名=值,实现set方法

<bean id="testService" class="com.dl.Service.TestService" p:resourceService-ref="resourceService" />

6.2 Spring IOC自动注入

6.2.1 准备环境
 xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd"
<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启自动注入-->
    <context:annotation-config/>
    <bean id="userDao" class="com.dl.dao.UserDao"/>
    <bean id="userService" class="com.dl.service.UserService"/>

</beans>
6.2.2 @Resource注解

@Resource实现bean对象的自动注入

1.默认会根据bean标签的id属性值查找(属性字段名与bean标签的id属性值相等)

2.如果属性名称未找到,则会根据类型(class)查找

3.属性字段可以提供set方法,也可以不提供。

4.注解可以声明在属性字段级别,或在set方法级别

public class UserService {
    @Resource
    private UserDao userDao;
    public void test() {
        System.out.println("UserService");
        userDao.test();
    }
}

5.可以设置注解的 name属性,name属性值必须与bean标签的id属性值一致

<bean id="ud" class="com.dl.dao.UserDao"/>
@Resource(name = "ud")
private UserDao userDao;

6.如果注入的是接口,接口只有一个实现类时,能正常注入。如果接口有多个实现类,则需要使用name属性设置id属性值

<context:annotation-config/>
<bean id="ud" class="com.dl.dao.UserDao"/>
<bean id="userService" class="com.dl.service.UserService"/>
<bean id="userDao01" class="com.dl.dao.UserDao01"/>
<bean id="userDao02" class="com.dl.dao.UserDao02"/>
@Resource
private UserDao01 userDao01;

public void test() {
    System.out.println("UserService");
    userDao.test();
    userDao01.test();
}
/*注入接口*/
@Resource
private IUserDao iUserDao;

public void test() {
    System.out.println("UserService");
    userDao.test();
    iUserDao.test();
}
/*注入接口*/
@Resource(name = "userDao01")
private IUserDao iUserDao;

public void test() {
    System.out.println("UserService");
    userDao.test();
    iUserDao.test();
}
6.2.3 @Autowired注解

1.默认通过类型(class)查找,与属性字段名无关

2.属性字段可以提供set方法,也可以不提供

3.注解可以声明在属性字段级别,或在set方法级别

4.如果需要设置属性字段通过id属性值查找,则需要结合@Qualifier注解使用,并设置@Qualifier的value属性值(value属性值和bean标签属性值保持一致)

@Autowired
private TypeDao typeDao;
@Autowired
@Qualifier(value = "td")
private TypeDao typeDao;
<!--开启自动注入-->
<context:annotation-config/>
<bean id="typeService" class="com.dl.service.TypeService"/>
<bean id="td" class="com.dl.dao.TypeDao"/>

七、Spring IOC扫描器

7.1 Spring IOC 扫描器的配置

1.设置自动化扫描的范围

2.使用指定的注解(声明在类级别)

Dao层:@Repository

Service层:@Service

Controller层:@Controller

任意类:@Component

<!--开启自动扫描,设置设置扫描包的范围-->
<context:component-scan base-package="com.dl"/>
@Controller
public class AccountController {
    @Resource
    private AccountService accountService;
    @Autowired
    private ProperUtil properUtil;
    public void test() {
        System.out.println("AccountController");
        accountService.test();
        properUtil.test();
    }
}

Spring IOC 扫描器

作用:可以对Bean对象进行统一的管理,简化配置信息,提高开发效率

使用:

1.在配置文件中开启自动扫描,设置扫描包范围

2.在需要被实例化的bean对象上添加指定的注解(声明在类疾病,bean对象的id属性默认是类的首字母小写)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值