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



}
相关推荐
IT爱学堂12 小时前
java版数据结构和算法+AI算法和技能学习指南
java·开发语言
evans在进步13 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
苍何13 小时前
偷偷分享 DeepSeek Harness 热榜挖到的 2 个实⽤插件
后端
神奇小汤圆13 小时前
面试官问:"你们上线前怎么测Agent系统?上线后怎么知道它好不好?"
后端
FfHUCisI13 小时前
Golang - 信号量模式(Semaphore Pattern)
开发语言·后端·golang
神奇小汤圆13 小时前
Redis 和 MySQL 如何保证数据一致性?先更新数据库还是先删缓存,延迟双删、MQ、Canal 一次讲透
后端
m0_5474866613 小时前
《Java程序设计与实践 》全套PPT课件2026
java·开发语言
土司大王14 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode
犹豫的果冻布丁14 小时前
从零给 DeepSeek Harness 写一个壁纸皮肤插件(已开源)
前端·后端
weixin_4316004414 小时前
NestJS 入门(10):日志——为什么常用 Winston?
后端·学习·日志·nest.js·winston