Spring学习之——IOC

IOC

概念

IOC (Inverse of Control)即控制反转:由ioc容器来创建依赖对象,程序只需要从IOC容器获取创建好的对象。

  • 原来:

​ 我们在获取对象时,都是采用new的方式。是主动的。

​

  • 现在:

​ 我们获取对象时,同时跟工厂要,有工厂为我们查找或者创建对象。是被动的。

​

​ 这种被动接收的方式获取对象的思想就是控制反转,它是spring框架的核心之一。

例子

1. pom.xml

java 复制代码
<dependencies>
        <!-- Spring常用依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
</dependencies>

2.DAO

java 复制代码
/**
 * 持久层实现类
 */
public class UserDaoImpl implements UserDao {

    @Override
    public void addUser(){
        System.out.println("insert into tb_user......");
    }
}

3.Service

java 复制代码
/**
 * 业务层实现类
 */
public class UserServiceImpl implements UserService {
    //此处有依赖关系
    private UserDao userDao = new UserDaoImpl();

    public void addUser(){
        userDao.addUser();
    }
}

4.applicationContext.xml

java 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!--1、注意:要导入schema约束-->
<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">
    
    <!--
		2、把对象交给spring来创建
       		id:给对象在容器中提供一个唯一标识。用于获取对象	
		   	class:指定类的全限定类名。用于反射创建对象。默认情况下调用无参构造函数
	-->
    <bean id="userDao" class="com.by.dao.UserDaoImpl"></bean>
    <bean id="userService" class="com.by.service.UserServiceImpl"></bean>
</beans>

5.测试

java 复制代码
/**
 * 模拟表现层
 */
public class Client {
    public static void main(String[] args) {
        //1.使用ApplicationContext接口,就是在获取spring容器
        ApplicationContext ac = new 
            ClassPathXmlApplicationContext("applicationContext.xml");
        //2.根据bean的id获取对象
        UserDao userDao = (UserDao) ac.getBean("userDao");
        System.out.println(userDao);

        UserService userService = (UserService) ac.getBean("userService");
        System.out.println(userService);
        userService.addUser();
    }
}

applicationContext.xml注意的细节

  1. 只配置class属性
java 复制代码
<bean class="com.by.pojo.User"/>

a) 上述这种配置 有没有id值 com.by.pojo.User#0

b) 应⽤场景:

  • 如果这个bean只需要使⽤⼀次,那么就可以省略id值

  • 如果这个bean会使⽤多次,或者被其他bean引⽤则需要设置id值

  • name属性

    作⽤:⽤于在Spring的配置⽂件中,为bean对象定义别名(⼩名)

    相同:

    ctx.getBean("id|name")-->object

    <bean id="" class=""

    等效

    <bean name="" class=""

    区别:

    1. 别名可以定义多个,但是id属性只能有⼀个值
    2. XML的id属性的值,命名要求:必须以字⺟开头,字⺟ 数字 下划线 连字符 不
      能以特殊字符开头 /person
      name属性的值,命名没有要求 /person
      name属性会应⽤在特殊命名的场景下
  • class属性

    写的是要创建对象的全限定名

  • Spring工厂的相关方法

    1. Object getBean(String key);
      通过这种⽅式获得对象,就不需要强制类型转换

    Person person = ctx.getBean("user", User.class);

    System.out.println("user = " + user);

    1. '<'T>T getBean(String key,Class requiredType);
      通过这种⽅式获得对象,就不需要强制类型转换

    Person person = ctx.getBean("user", User.class);

    System.out.println("user = " + user);

    1. '<'T>T getBean(Class requiredType);
      当前Spring的配置⽂件中 只能有⼀个<bean class是Person类型

    Person person = ctx.getBean(Person.class);

    System.out.println("person = " + person);

    1. String\[\] getBeanDefinitionNames()
      获取的是 Spring⼯⼚配置⽂件中所有bean标签的id值 person person1

    String\[\] beanDefinitionNames = ctx.getBeanDefinitionNames();

    for (String beanDefinitionName : beanDefinitionNames) {

    System.out.println("beanDefinitionName = " +beanDefinitionName);

    }

    1. String\[\] getBeanNamesForType(Class requiredType);
      根据类型获得Spring配置⽂件中对应的id值

    String\[\] beanNamesForType = ctx.getBeanNamesForType(Person.class);

    for (String id : beanNamesForType) {

    System.out.println("id = " + id);

    }

    1. boolean containsBeanDefinition(string key);
      ⽤于判断是否存在指定id值得bean

    if (ctx.containsBeanDefinition("a")) {

    System.out.println("true = " + true);

    }else{

    System.out.println("false = " + false);

    }

    1. boolean containsBean(String key);
      ⽤于判断是否存在指定id值得bean

    if (ctx.containsBean("person")) {

    System.out.println("true = " + true);

    }else{

    System.out.println("false = " + false);

    }

相关推荐
两点王爷2 小时前
Java 面试高频:JWT、Cookie、Session、Token 鉴权详解
java·开发语言·面试
悟道书生3 小时前
hashMap/hashSet/hashCode详解
java
楚山之石4 小时前
【Lancet】BRAID 随机试验:乳腺致密女性补充成像,abbreviated MRI 与 CEM 检出更多早期癌(首轮中期结果)
人工智能·科技·学习·mri·医学影像
nice_lcj5205 小时前
依赖注入的三种方式:构造器、Setter、字段怎么选
java·spring·面试·依赖注入·字段注入·构造器注入
噢,我明白了5 小时前
实际项目导出方式应用
java·状态模式·导出
جيون داد ناالام ميづ6 小时前
七、MyBatis 源码剖析:核心流程拆解(初始化 + SQL 执行)
java·sql·mybatis
考虑考虑6 小时前
Spingboot4.2.0中的属性
spring boot·后端·spring
ClkLog-开源埋点用户分析6 小时前
【产品说明】【埋点分析】ClkLog 商业版 Java 运行环境安全更新说明
java·开发语言
秋饼6 小时前
Spring Framework 7 内置弹性实战:@Retryable 语义翻转、虚拟线程流量放大与 LLM 网关治理
java·ai·技术分享·后端开发