spring 获取ioc容器,从容器中获取bean

复制代码
package com.example.demo;

import com.example.demo.service.MyService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@SpringBootTest
class DemoApplicationTests {

   @Test
   void contextLoads() {
             //指定bean 所在的包
      AnnotationConfigApplicationContext context
            = new AnnotationConfigApplicationContext("com.example.demo");
//        context.refresh(); // 初始化 Spring 容器
      // ... 获取和使用 Bean ...
//    context.close();
      MyService bean1 = context.getBean(MyService.class);
      MyService bean2 = context.getBean(MyService.class);

      System.out.println("bean1 hashCode: " + bean1.hashCode());
      System.out.println("bean2 hashCode: " + bean2.hashCode());

      if (bean1 == bean2) {
         System.out.println("bean1 and bean2 are the same instance.");
      } else {
         System.out.println("bean1 and bean2 are not the same instance.");
      }
   }



}
相关推荐
Moment2 分钟前
为什么 Tiptap 做协同编辑离不开 Hocuspocus❓❓❓
前端·后端·面试
装不满的克莱因瓶5 分钟前
深入理解 Redisson 原理:Redis 不只是缓存,更是分布式协调器
java·redis·分布式·架构·分布式锁·redisson
pixelpilot16 分钟前
微软常用运行库directx修复工具(directx repair)2026版directx下载下载安装教程
java·开发语言·其他·microsoft
曾几何时`9 分钟前
Go(二)Goroutine及GMP模型
开发语言·后端·golang
码luffyliu10 分钟前
企业级多agent知识库系统|超值源码+资料
java·agent·秋招·实习·rag·知识库系统
wang090711 分钟前
自己动手写一个spring之IOC_1
java·后端·spring
garmin Chen11 分钟前
Prompt工程入门:让AI按你的要求工作(1)--prompt概述与设计
java·人工智能·python·junit·prompt·agent
江湖中的阿龙15 分钟前
Go语言零基础入门教程(一)环境搭建与基础入门
开发语言·后端·golang
集成显卡8 小时前
Rust实战七 |基于带 colored 颜色文字控制台的批量文件删除工具
开发语言·后端·rust