Spring 控制反转(IOC)

一、添加 Maven 依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>

二、创建实体类

public class IOCBean {
	...
}

三、创建 Spring 配置文件

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

    <bean id="iocBean" class="chu.yi.bo.IOCBean"/>
</beans>

四、Bean 标签

      作用:

      用于配置对象交由 spring 框架来创建,默认情况下调用的是类中的无参构造函数。如果没有无参构造函数则不能创建成功。

      属性:

  • id                         :给对象在容器中提供一个唯一标识。用于获取对象
  • class                    :指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数。
  • init-method        :指定类中的初始化方法名称
  • destroy-method :指定类中销毁方法名称
  • scope                  :指定对象的作用范围
属性值说明
singleton单例,默认值
prototype多例
requestWEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 request 域中
sessionWEB 项目中,Spring 创建一个 Bean 的对象,将对象存入到 session 域中
global sessionWEB 项目中,应用在 Portlet 环境.如果没有 Portlet 环境那么 globalSession 相当于 session

五、测试

public void testSpring() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Application.xml");
    IOCBean aService = (IOCBean) applicationContext.getBean("iocBean");
}

六、Spring 容器
      将实体类交由 Spring 框架管理后,Spring 容器负责这些类实例的创建、装配、销毁。BeanFactory 接口、ApplicationContext 接口是 Spring 框架的两个核心容器。ApplicationContext 接口继承 BeanFactory 接口。

      两者区别:

容器说明
BeanFactory对象被使用时才会创建对象
ApplicationContext只要读取配置文件就会创建对象

      ApplicationContext 接口实现类:

实现类说明
ClassPathXmlApplicationContext从类的根路径下加载配置文件
FileSystemXmlApplicationContext从磁盘路径上加载配置文件
AnnotationConfigApplicationContext使用注解配置容器对象时,需要使用此类来创建 spring 容器
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值