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

	}

}
相关推荐
NAGNIP3 小时前
多个 GitHub 账户SSH 密钥配置全攻略
后端
NAGNIP3 小时前
Windows命令行代码自动补全详细步骤
后端
.鸣3 小时前
set和map
java·学习
追逐时光者4 小时前
精选 8 款 .NET 开源、前后端分离的快速开发框架,提高开发生产效率!
后端·.net
ha_lydms4 小时前
5、Spark函数_s/t
java·大数据·python·spark·数据处理·maxcompute·spark 函数
用户47949283569154 小时前
性能提升 4000%!我是如何解决 运营看板 不能跨库&跨库查询慢这个难题的
数据库·后端·postgresql
黄河滴滴4 小时前
java系统变卡变慢的原因是什么?从oom的角度分析
java·开发语言
侠客行03174 小时前
Mybatis二级缓存实现详解
java·mybatis·源码阅读
老华带你飞5 小时前
农产品销售管理|基于java + vue农产品销售管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
Edward111111115 小时前
tomcat_servlet
java·servlet·tomcat