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.");
      }
   }



}
相关推荐
圆山猫2 小时前
[Virtualization](四):Linux KVM/RISC-V 的 vCPU 运行路径
java·linux·risc-v
城管不管2 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
IT小白杨2 小时前
从环境制备到自动化工作流:多账号运营的工程化架构拆解
java·经验分享·自动化·安全架构·指纹浏览器
豆瓣鸡3 小时前
算法日记 - Day3
java·开发语言·算法
萧瑟余晖3 小时前
Java深入解析篇九之NIO详解
java·网络·nio
mldong3 小时前
从 mldong 到 jeeflow:一个工作流引擎的独立进化
后端
The Chosen One9853 小时前
高进度算法模板速记(待完善)
java·前端·算法
陈随易3 小时前
MoonBit抓包模块pcap,查看电脑的每一次联网通信
前端·后端·程序员
Aaron - Wistron4 小时前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
卷无止境4 小时前
写代码这件事,到底该讲究点什么?
后端·python