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

	}

}
相关推荐
程序员爱钓鱼5 分钟前
Go语言实战指南 —— Go中的反射机制:reflect 包使用
后端·google·go
ℳ₯㎕ddzོꦿ࿐10 分钟前
Spring Boot 集成 MinIO 实现分布式文件存储与管理
spring boot·分布式·后端
2301_803554521 小时前
c++中类的前置声明
java·开发语言·c++
不想写bug呀4 小时前
多线程案例——单例模式
java·开发语言·单例模式
心平愈三千疾5 小时前
通俗理解JVM细节-面试篇
java·jvm·数据库·面试
我不会写代码njdjnssj5 小时前
网络编程 TCP UDP
java·开发语言·jvm
第1缕阳光5 小时前
Java垃圾回收机制和三色标记算法
java·jvm
funnyZpC5 小时前
好用的文档工具👉smart-doc
java
ai小鬼头5 小时前
百度秒搭发布:无代码编程如何让普通人轻松打造AI应用?
前端·后端·github
考虑考虑5 小时前
@FilterRegistration和@ServletRegistration注解
spring boot·后端·spring