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



}
相关推荐
bearpping3 分钟前
Java进阶,时间与日期,包装类,正则表达式
java
邵奈一9 分钟前
清明纪念·时光信笺——项目运行指南
java·实战·项目
sunwenjian88628 分钟前
Java进阶——IO 流
java·开发语言·python
sinat_2554878138 分钟前
读者、作家 Java集合学习笔记
java·笔记·学习
墨香幽梦客42 分钟前
API集成技术规范:RESTful与GraphQL在企业系统对接中的应用对比
后端·restful·graphql
皮皮林5511 小时前
如何画出一张优秀的架构图?(老鸟必备)
java
百锦再1 小时前
Java 并发编程进阶,从线程池、锁、AQS 到并发容器与性能调优全解析
java·开发语言·jvm·spring·kafka·tomcat·maven
森林猿1 小时前
java-modbus-读取-modbus4j
java·网络·python
tobias.b1 小时前
计算机基础知识-数据结构
java·数据结构·考研
reembarkation2 小时前
光标在a-select,鼠标已经移出,下拉框跟随页面滚动
java·数据库·sql