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



}
相关推荐
ayqy贾杰13 小时前
基层管理的三板斧,在AI时代行不通了
前端·后端·团队管理
Apifox13 小时前
Apifox 5 月更新|Postman 导入优化、Runner 支持非 root 运行、请求代码自动带鉴权
前端·后端·安全
云烟成雨TD13 小时前
Spring AI 1.x 系列【33】RAG Advisor 组件与四大分层架构
java·人工智能·spring
JohnYan14 小时前
工作笔记 - PG分组极值
数据库·后端·postgresql
J2虾虾14 小时前
Spring AI Alibaba - Tools
服务器·人工智能·spring
雪隐14 小时前
AI股票小助手02-Akshare数据采集
人工智能·后端
江南十四行14 小时前
并发编程(七)
java
清溪54915 小时前
pgAdmin4 <= 9.1_RCE(CVE-2025-2945)复现
数据库·后端
亦暖筑序15 小时前
单模型成本高、风险大?Spring AI多模型路由实战:成本降70%,可用性更稳
java·后端·ai编程
404号扳手15 小时前
Java 进阶知识(二)
java·后端