持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第19天,点击查看活动详情
2.2、基于XML管理bean
1.创建Maven Module
2.引入依赖
<dependencies>
<!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<!-- 更多Java –大数据 – 前端 – UI/UE - Android - 人工智能资料下载,可访问百度:尚硅谷官网(www.atguigu.com)-->
<!-- ③创建类HelloWorld-->
<!-- ④创建Spring的配置文件-->
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
3.创建类HelloWorld
package com.atguigu.spring.pojo;/**
* @author zzw
* @version 1.0
* Create by 2022/10/15 17:17
*/
/**
* @author zzw
* @version 1.0
* Create by 2022/10/15 17:17
*/
public class HelloWorld {
public void sayHello(){
System.out.println("hello spring");
}
}
4.创建Spring的配置文件
spring中配置的bean对象
测试类
package com.atguigu.spring.test;/**
* @author zzw
* @version 1.0
* Create by 2022/10/15 17:25
*/
import com.atguigu.spring.pojo.HelloWorld;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author zzw
* @version 1.0
* Create by 2022/10/15 17:25
*/
public class HelloWorldTest {
@Test
public void test(){
//获取容器
//applicationContext是ClassPathXmlApplicationContext的父类接口
//通过向上转型 即父类对象的引用指向子类对象
ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取ioc容器中的bean对象
//通过唯一标识得到对象 并进行强转
HelloWorld helloworld = (HelloWorld) ioc.getBean("helloworld");
helloworld.sayHello();
}
}
在ioc容器中就是通过反射和工厂模式去创建对象的
一般出现这种情况就是实体类中没有定义无参
Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'helloworld' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.atguigu.spring.bean.HelloWorld]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.atguigu.spring.bean.HelloWorld.()
获取bean的方式
获取bean的三种方式 1.根据bean的id获取 2.根据bean的类型 注意根据类型获取bean时,要求ioc容器中有且只有一个类型匹配的bean 若没有任何一个类型匹配的bean,此时抛出异常:NoSuchBeanDefinitionException 若有个多个类型匹配的bean,此时抛出异常:NoUniqueBeanDefinitionException 3.根据bean的id和类型获取 注意 当根据类型获取bean时 要求ioc容器中指定类型的bean有且只能有一个 当IOC容器中一共配置两个 如果组件类实现了接口,根据接口类型可以获取bean吗? 可以,前提时bean唯一 如果一个接口有多个实现类,这些实现类都配置了bean,根据接口类型可以获取bean吗? 不行,因为bean不唯一 根据类型来获取bean时,在满足bean唯一性的前提下 其实只是看:[对象 ** instanceof** 指定的类型] 的返回结果 只要返回的是true就可以认定为和类型匹配,能够获取到 即通过bean的类型,bean所继承的类的类型,bean所实现的接口的类型都可以 获取bean
三种方式截图
// 根据唯一标识id Student student = (Student) ioc.getBean("student");
// 根据类型获取 Student student = ioc.getBean(Student.class);
// 根据id和类型 Student studentOne = ioc.getBean("studentOne", Student.class);
两个异常的截图