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);

	}

}
相关推荐
GoGeekBaird1 天前
Prompt、Context、Harness 工程全景图
后端
SimonKing1 天前
艹,维护AI写的代码,我心态崩了......
java·后端·程序员
AskHarries1 天前
MCP 基础:Server、Tool、Resource 和 Prompt
后端·程序员
长栎1 天前
你写的 DCL 单例,在反序列化面前就是个弟弟——单例模式的破局与重建
后端
长栎1 天前
命令模式和策略模式代码长一样——你分不清是因为你没看穿它们的本质
后端
用户298698530141 天前
Java Word 文档样式进阶:段落与文本背景色设置完全指南
java·后端
苍何1 天前
开源个狠活,世界杯 AI 模型竞技场!
后端
Dilee1 天前
Spring AI 1.1.7 接入 MCP:Filesystem Server 最小 Demo
人工智能·后端
程序员小富1 天前
我开源了一个开发者专属的智能 JSON 工具,得到了媳妇高度认可
前端·vue.js·后端