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



}
相关推荐
zzzsde3 分钟前
【C++】深入理解string类(5)
java·前端·算法
失散136 分钟前
分布式专题——46 ElasticSearch高级查询语法Query DSL实战
java·分布式·elasticsearch·架构
程序员鱼皮9 分钟前
为什么下载小电影时,进度总是卡在99%?
java·计算机·程序员·互联网·编程
没有bug.的程序员24 分钟前
分布式链路追踪:微服务可观测性的核心支柱
java·分布式·微服务·架构·wpf
我是华为OD~HR~栗栗呀27 分钟前
华为OD-21届考研-Java面经
java·前端·c++·python·华为od·华为·面试
陈随易28 分钟前
不使用 Husky 和 Lint-staged,实现 Git 提交前自动格式化代码
前端·后端·程序员
凤山老林29 分钟前
SpringBoot 启动时执行某些操作的 8 种方式
java·开发语言·spring boot·后端
莹Innsane41 分钟前
重新认识 Golang 中的 json 编解码
后端
东百牧码人41 分钟前
MySqlConnection is already in use是什么原因
后端
白衣鸽子43 分钟前
【基础数据篇】数据访问守卫:Accessor模式
后端·设计模式