可以通過實現(xiàn)BeanDefinitionRegistryPostProcessor接口,它的父接口是BeanFactoryPostProcessor.
步驟:
一、自定義一個組件類:
package com.example.demo.service;
public class MusicService {
public MusicService() {
System.out.println("music service constructed!");
}
}
二、定義類實現(xiàn)BeanDefinitionRegistryPostProcessor:文章來源:http://www.zghlxwxcb.cn/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文章來源地址http://www.zghlxwxcb.cn/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);
}
}
到了這里,關(guān)于SpringBoot復(fù)習(xí):(20)如何把bean手動注冊到容器?的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!