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



}
相关推荐
Yunzenn12 小时前
深度解析字节前沿研究-Cola DLM第 04 章:Cola DLM 架构全景 —— 三层解耦的设计哲学
java·linux·python·深度学习·面试·github·transformer
Gopher_HBo12 小时前
JVM垃圾收集算法和垃圾收集器
后端
MepSUxjvy12 小时前
拆解 OpenHands(11)--- Runtime主要组件
java·windows·microsoft
IT_陈寒12 小时前
SpringBoot自动配置偷偷给我埋了个坑
前端·人工智能·后端
ch.ju12 小时前
Java Programming Chapter 4——Member method
java·开发语言
笨蛋不要掉眼泪12 小时前
Java并发编程:ReentrantLock与AQS原理剖析
java·开发语言·并发
心.c12 小时前
CommonJS和ES Module
javascript·后端·node.js
兰令水12 小时前
topcode【随机算法题】【2026.5.22打卡-java版本】
java·算法·leetcode
Dicky-_-zhang12 小时前
敏感数据加密存储实战
java·jvm
念何架构之路12 小时前
Go依赖管理
开发语言·后端·golang