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



}
相关推荐
杨杨杨大侠8 分钟前
Java 不再需要 JVM?一文看懂 GraalVM Native Image、Substrate VM 与 JDK
java·jvm·java ee
GoGeekBaird10 分钟前
(万字长文拆解云沙箱)让 Agent 从执行代码升级到拥有一个临时Runtime
后端·agent
torin13 分钟前
Javaer转Agent:学习资料篇
后端·agent
Sylvia33.21 分钟前
火星数据体育API|一站式接入足球篮球电竞等18+项目实时数据
java·开发语言·python·websocket·游戏
李少兄27 分钟前
解决 MySQL Lock wait timeout exceeded 报错
java
va学弟28 分钟前
Java 语言特性:泛型(Generics)
java·泛型
SL_staff1 小时前
插单风险的数据闭环治理:JVS-BI 在制造业实时预警中的技术实践
java·数据分析·数据可视化
cidy_981 小时前
07 — Service 层:业务逻辑
后端
苍何1 小时前
用 GPT6 + Hyper3D MCP 搓 3D 个人网站,太夯了!(附教程)
后端
cidy_981 小时前
05 — 分层架构设计思想
后端