ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
案例代码:https://gitee.com/flymini/codes03/tree/master/learn-bootioc **** 自定义 IoC 容器有如下两种方式: [TOC] # 1. 引入Spring配置文件 下面将 AccountServiceImpl 类注册到 Spring 的配置文件中。步骤如下: **1. AccountServiceImpl 类** ```java public class AccountServiceImpl { public void printUsername() { System.out.println("[printUsername]"); } } ``` <br/> **2. 在 Spring 配置文件`ApplicationContext.xml` 中注册 AccountServiceImpl** ```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="accountService" class="learn.bootioc.service.impl.AccountServiceImpl"/> </beans> ``` <br/> **3. 在启动类上标注注解`@ImportResource`引入 Spring 配置文件** ```java @SpringBootApplication @ImportResource({"classpath:ApplicationContext.xml"}) public class IocApplication { public static void main(String[] args) { SpringApplication.run(IocApplication.class, args); } } ``` <br/> **4. 测试** ```java @SpringBootTest class IocApplicationTests { @Autowired private ApplicationContext applicationContext; @Test public void testIoc1() { //从IoC容器中获取AccountServiceImpl对象 AccountServiceImpl accountService = applicationContext.getBean(AccountServiceImpl.class); accountService.printUsername(); //[printUsername] } } ``` <br/> # 2. 将一个类定义为IoC容器 下面将 StudentServiceImpl 类注册到自定义的 IoC 容器中。步骤如下: **1. StudentServiceImpl 类** ```java public class StudentServiceImpl { public void printUsername() { System.out.println("[printUsername]"); } } ``` <br/> **2. 类上标注注解`@Configuration`将该类定义为 IoC 容器** ```java @Configuration public class CustomIocConfig { /** * 将StudentServiceImpl注册到当前的IoC容器中 * * @Bean注解的作用:<bean id="方法名" class="方法的返回值"/> */ @Bean public StudentServiceImpl studentService() { return new StudentServiceImpl(); } } ``` <br/> **3. 测试** ```java @SpringBootTest class IocApplicationTests { @Test void testIoc2() { //获取IoC容器 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CustomIocConfig.class); //从IoC容器中拿到StudentServiceImpl对象 StudentServiceImpl impl = context.getBean(StudentServiceImpl.class); impl.printUsername(); //StudentServiceImpl } } ```