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



}
相关推荐
苏三说技术19 小时前
LangChain4j 和 LangGraph4j,哪个更好?
后端
ServBay20 小时前
7 个AI开发中真正用得上的 MCP Server,配合Claude Code食用效果更佳
后端·claude·mcp
妙码生花20 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
用户67570498850221 小时前
Go 语言里判断字符串为空,90% 的人都写错了!
后端·go
Flittly21 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
用户67570498850221 小时前
Go 进阶必修:90% 的人都没用对的“表驱动法”
后端·go
小兔崽子去哪了21 小时前
Java 生成二维码解决方案
java·后端
苍何21 小时前
懂事的 Agent 已经开始自己看屏幕干活了,效率起飞!
后端
掘金码甲哥21 小时前
1分钟买不了吃亏系列: nginx动态域名解析
后端