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



}
相关推荐
z落落5 分钟前
C# 多接口实现、重名成员、显式实现、接口继承+抽象类和接口区别
java·开发语言·c#
C137的本贾尼13 分钟前
【实战】分析一张真实业务表的 InnoDB 存储结构
java·大数据·数据库
超梦dasgg15 分钟前
亿级数据 不停服务平滑迁移(生产环境实战方案)
java·数据库
Zella折耳根17 分钟前
Java 正则表达式实战:IP 地址匹配与替换全解析
java·tcp/ip·正则表达式
摇滚侠17 分钟前
JavaWeb 全套教程 Filter 107-111
java·开发语言·servlet
YIN_尹20 分钟前
【Linux系统编程】基础IO第一讲——系统文件IO
android·java·linux·c++
凤山老林20 分钟前
81-Java Scanner 类
java·开发语言
糖果店的幽灵21 分钟前
Spring AI 从入门到精通-ChatClient你与 AI 对话的终极武器
人工智能·python·spring
linge_sun22 分钟前
Sping AI 使用 Ollama 快速搭建本地知识库
java·人工智能·ai编程
沐苏瑶23 分钟前
深入浅出 Java 文件操作与 IO:从文件系统到数据流实战
java·开发语言