魔术桌
  • 更新日志
  • 新闻资讯
  • 数据资产
  • 网站导航
  • 订阅推荐
  • 商品推广
  • 日记
  • 摘录
  • 论文
  • 方案
  • 技术
  • 风格
  • 视觉
  • 原材料
  • 加工工艺
  • 元器件
  • 产品设备
  • 设计模式
  • 数据结构
  • 算法设计
  • 软件架构
  • 程序语言
  • 代码类库
  • 操作系统
  • 软件包
  • 健康
  • 环境
  • 社会
  • 道德
  • 法律
  • 经济
  • 政策
  • 更新日志
  • 新闻资讯
  • 数据资产
  • 网站导航
  • 订阅推荐
  • 商品推广
  • 日记
  • 摘录
  • 论文
  • 方案
  • 技术
  • 风格
  • 视觉
  • 原材料
  • 加工工艺
  • 元器件
  • 产品设备
  • 设计模式
  • 数据结构
  • 算法设计
  • 软件架构
  • 程序语言
  • 代码类库
  • 操作系统
  • 软件包
  • 健康
  • 环境
  • 社会
  • 道德
  • 法律
  • 经济
  • 政策
  • Library - Maven - SpringFramework 6 - spring容器

文章摘要: 摘要内容。

spring容器

org.springframework.context.annotation.AnnotationConfigApplicationContext

  • 通过注解的方式配置spring容器

org.springframework.context.support.ClassPathXmlApplicationContext

  • 通过xml文件来配置spring容器

步骤

  1. 创建spring容器
  2. 配置spring容器
  3. 启动spring容器

案例

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import tech.magictable.service.config.SpringConfig;

public class Application {

    public static void main(String[] ages) {
        // 创建spring容器,Java配置类
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        // 将用作配置类的类名注册到spring容器中,即spring容器将到该配置类中读取相关注解
        applicationContext.register(SpringConfig.class);

        // 启动spring容器
        applicationContext.refresh();
    }
}

编写配置类

@ComponentScan(“<包路径>”)

  • 扫描包路径。
  • org.springframework.context.annotation.ComponentScan

标识类为Bean对象

在一个类上一行上编写@Component注解,将由配置文件中的扫描包路径读取并注册到spring容器中。

获取Bean对象

  • applicationContext.getBean(<类名>.class):从spring容器中获取对象。

更新时间: 2025/11/16 17:17