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



}
相关推荐
爱上语文1 分钟前
Redis基础(4):Set类型和SortedSet类型
java·数据库·redis·后端
lifallen15 分钟前
Paimon vs. HBase:全链路开销对比
java·大数据·数据结构·数据库·算法·flink·hbase
笑衬人心。1 小时前
初学Spring AI 笔记
人工智能·笔记·spring
深栈解码1 小时前
JMM深度解析(三) volatile实现机制详解
java·后端
张家宝68371 小时前
ambari
后端
StephenCurryFans1 小时前
Spring AI vs LangChain4j:Java AI开发框架完整对比指南 🚀
后端·spring
liujing102329291 小时前
Day04_刷题niuke20250703
java·开发语言·算法
程序员辉哥1 小时前
学会在Cursor中使用Rules生成代码后可以躺平了吗?
前端·后端
Brookty1 小时前
【MySQL】JDBC编程
java·数据库·后端·学习·mysql·jdbc
_代号0071 小时前
MySQL梳理一:整体架构概览
后端·mysql