0.配置pom.xml文件
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.1</version>
</dependency>
</dependencies>
1.编写组件类CustomComponent1.java
package com.my.ioc_01;
public class CustomComponent1 {
// 默认包含无参构造函数
public void customMethod() {
System.out.println("这是组件类的一个自定义方法");
}
}
2.编写配置文件applicationContext.xml
在resources目录下新建applicationContext.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="customComponent1" class="com.my.ioc_01.CustomComponent1" />
</beans>
3.创建Spring IoC容器
在创建IoC容器之前,需要选择合适的容器实现类
实现类 | 用途 |
ClassPathXmlApplicationContext | 读取类路径下的xml的配置方式 |
AnnotationConfigApplicationContext | 读取Java类的配置方式 |
WebApplicationContext | web项目专属的配置方式 |
本例程将xml文件放在了resources目录下,也就是放在了被编译后的类目录classes目录下,因此选用ClassPathXmlApplicationContext实现类来创建Spring IoC容器.
/**
* 选择合适的容器实现类,创建Spring IoC容器
*/
public ApplicationContext createIoc() {
// 此处配置文件可填写多个
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
return context;
}
4.使用组件类对象
在使用组件类对象之前,我们需要先获取组件类对象,获取组件类对象需要调用getBean方法
获取到组件类对象之后,我们只需调用组件类对象的相应方法就可以了.
/**
* 通过Spring IoC容器获取组件类对象
*/
public CustomComponent1 getBean() {
ApplicationContext context = createIoc();
CustomComponent1 customComponent1 = context.getBean("customComponent1", CustomComponent1.class);
return customComponent1;
}
/**
* 使用从Spring IoC获取到的组件类对象
*/
@Test
public void useBeans() {
CustomComponent1 customComponent1 = getBean();
customComponent1.customMethod();
}