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



}
相关推荐
Flynn Liang39 分钟前
RAG 评估体系:黄金集、检索指标与 LLM-as-Judge 落地
java·langchain·rag·评估·langchain4j·检索指标
SomeOtherTime44 分钟前
Rust生命周期介绍(AI回答)
开发语言·后端·rust
无责任此方_修行中1 小时前
「不止技术」AIE 2026 会后感悟
人工智能·后端·ai编程
SimonKing2 小时前
Workbuddy太占C盘空间了,写个迁移工具迁走10G的数据
java·后端·程序员
Hvitur2 小时前
Java - Lambda
java·开发语言·python
喵了几个咪3 小时前
GoWind Flow 拆解:一个 Go 工作流引擎与它的双模式设计器
开发语言·人工智能·后端·golang
倔强的石头_3 小时前
AI数据库是什么?我把金仓KES的库内三件套拆开看了一遍
后端
杨凯凡3 小时前
Spring Boot 大文件下载如何实现断点续传?HTTP Range、206 与 416 实战
spring boot·后端·http
量化分析码农3 小时前
股票实时行情接口返回字段说明:单次请求的时间字段与数值类型
后端