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

	}

}
相关推荐
黛色正浓几秒前
leetCode-热题100-普通数组合集(JavaScript)
java·数据结构·算法
月明长歌4 分钟前
Java多线程线程池ThreadPoolExecutor理解总结:6 个核心参数 + 4 种拒绝策略(附完整示例)
java·开发语言
找不到、了5 分钟前
JVM 跨代引用与 Card Table 机制
java·jvm
sunywz7 分钟前
【JVM】(2)java类加载机制
java·jvm·python
进阶小白猿13 分钟前
Java技术八股学习Day13
java·jvm·学习
CodeAmaz19 分钟前
ConcurrentHashMap(JDK 7/8)详细介绍
java·hashmap·线程安全map
大猫和小黄21 分钟前
Tomcat vs Undertow 全面对比
java·tomcat
大橙子打游戏24 分钟前
OpenCode真的可以挑战Claude Code
后端
苏三说技术28 分钟前
如何设计一个高并发系统?
后端