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



}
相关推荐
柒和远方10 分钟前
从审计日志到可下载证据包:事务型 Outbox、租约 fencing 与保留水位
前端·后端·架构
卓怡学长16 分钟前
w266基于spring boot + vue 圣地延安美食乐享系统
java·数据库·vue.js·spring boot·spring·intellij-idea
C++、Java和Python的菜鸟40 分钟前
第7章 Java高级技术
java·开发语言
程序员佳佳1 小时前
模型网关灰度不是调百分比:把放量、观测和回滚做成账本
java·数据库·人工智能·redis·gpt·aigc·embedding
geovindu1 小时前
CSharp: Prototype Pattern
开发语言·后端·设计模式·.net·原型模式·创建型模式
Listen·Rain2 小时前
Springboot整合Ollama实现调用本地多模型
java·spring boot·后端
霸道流氓气质2 小时前
Java 工程师 AI 智能体(Agent)完整学习路线
java·人工智能·学习
aaPIXa6222 小时前
C++模板元编程:编译期计算Fibonacci数列
java·开发语言·c++
SunnyDays10112 小时前
Java 编辑 PDF:从增删改查到加密保护
java·修改 pdf·编辑 pdf
张三丰23 小时前
Agent 不只是聊天框:用 ArkUI 做一个鸿蒙任务工作台
后端