SpringBoot复习:(20)如何把bean手动注册到容器?

可以通过实现BeanDefinitionRegistryPostProcessor接口,它的父接口是BeanFactoryPostProcessor.

步骤:

一、自定义一个组件类:

复制代码
package com.example.demo.service;


public class MusicService {
    public MusicService() {
        System.out.println("music service constructed!");
    }
}

二、定义类实现BeanDefinitionRegistryPostProcessor:

复制代码
package com.example.demo.component;

import com.example.demo.service.MusicService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.stereotype.Component;

@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        System.out.println(registry.getBeanDefinitionCount());
        //定义BeanDefinition对象
        RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(MusicService.class);
        //将BeanDefinition对象注册到容器
        registry.registerBeanDefinition("musicBean", rootBeanDefinition);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println( beanFactory.getBeanDefinitionCount() );
    }
}

通过@Component注解,Spring就能够扫描到MyBeanDefinitionRegistryPostProcessor,也就能够把MusicService这个组件注册到容器。

三、可以获取在容器中通过MyBeanDefinitionRegistryPostProcessor注册的bean

复制代码
package com.example.demo;

import com.example.demo.service.MusicService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.PropertySource;

@SpringBootApplication
@PropertySource("classpath:my.properties")
public class DemoApplication {

	public static void main(String[] args) {
		ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
		System.out.println("abc");

		MusicService musicService = context.getBean("musicBean", MusicService.class);
		System.out.println(musicService);

	}

}
相关推荐
Java水解15 分钟前
Rust嵌入式开发实战——从ARM裸机编程到RTOS应用
后端·rust
AI探索者18 分钟前
LangGraph 条件路由:构建支持工具调用的智能 Agent
后端
苍何20 分钟前
终于,我把 Openclaw 加 Seed2.0 Skills 做 AI 漫剧搞定了
后端
Derek_Smart27 分钟前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
苍何35 分钟前
阿里出手,最强Coding Plan出炉,OpenClaw可以痛快玩了
后端
风象南1 小时前
Claude Code这个隐藏技能,让我告别PPT焦虑
人工智能·后端
神奇小汤圆1 小时前
为什么 Spring 强烈推荐你用 singleton
后端
NE_STOP1 小时前
MyBatis-mybatis入门与增删改查
java
Java编程爱好者1 小时前
面试必问:Semaphore 凭什么靠 AQS + CAS 实现限流?
后端