可以通过实现BeanDefinitionRegistryPostProcessor接口,它的父接口是BeanFactoryPostProcessor.
步骤:
一、自定义一个组件类:
package com.example.demo.service;
public class MusicService {
public MusicService() {
System.out.println("music service constructed!");
}
}
二、定义类实现BeanDefinitionRegistryPostProcessor:文章来源:https://www.toymoban.com/news/detail-628688.html
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文章来源地址https://www.toymoban.com/news/detail-628688.html
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);
}
}
到了这里,关于SpringBoot复习:(20)如何把bean手动注册到容器?的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!