面试官:将 Bean 放入 Spring 容器中的方式有哪些 ?
以下文章来源Java架构师技术,回复”Spring“获惊喜礼包
上一篇推文:20K Star,这款微信插件太好用了!
大家好,我是Java架构师
我们知道平时在开发中使用Spring的时候,都是将对象交由Spring去管理,那么将一个对象加入到Spring容器中,有哪些方式呢,下面我就来总结一下
1、@Configuration + @Bean
这种方式是我们最常用的一种方式,
@Configuration
用来声明一个配置类,然后使用@Bean
注解,用于声明一个bean,将其加入到Spring容器中。具体代码如下:
@Configuration
publicclassMyConfiguration{
@Bean
public Person person(){
Person person = new Person();
person.setName("spring");
return person;
}
}
2、@Componet + @ComponentScan
这种方式也是我们用的比较多的方式,
@Componet
中文译为组件,放在类名上面,然后@ComponentScan
放置在我们的配置类上,然后可以指定一个路径,进行扫描带有@Componet
注解的bean,然后加至容器中。具体代码如下:
@Component
publicclassPerson{
private String name;
public String getName(){
return name;
}
publicvoidsetName(String name){
this.name = name;
}
@Override
public String toString(){
return"Person{" +
"name='" + name + '\'' +
'}';
}
}
@ComponentScan(basePackages = "com.springboot.initbean.*")
publicclassDemo1{
publicstaticvoidmain(String[] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
}
}
结果输出:
Person{name='null'}
表示成功将Person放置在了IOC容器中。
3、@Import注解导入
前两种方式,大家用的可能比较多,也是平时开发中必须要知道的,
@Import
注解用的可能不是特别多了,但是也是非常重要的,在进行Spring扩展时经常会用到,它经常搭配自定义注解进行使用,然后往容器中导入一个配置文件。关于
@Import
注解,我会多介绍一点,它有四种使用方式。这是@Import
注解的源码,表示只能放置在类上。另外,搜索公众号Linux就该这样学后台回复“猴子”,获取一份惊喜礼包。@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public@interface Import {
/**
* 用于导入一个class文件
* {@link Configuration @Configuration}, {@link ImportSelector},
* {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
*/
Class<?>[] value();
}
3.1 @Import直接导入类
代码示例如下:
publicclassPerson{
private String name;
public String getName(){
return name;
}
publicvoidsetName(String name){
this.name = name;
}
@Override
public String toString(){
return"Person{" +
"name='" + name + '\'' +
'}';
}
}
/**
* 直接使用@Import导入person类,然后尝试从applicationContext中取,成功拿到
**/
@Import(Person.class)
publicclassDemo1{
publicstaticvoidmain(String[] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
}
}
上述代码直接使用
@Import
导入了一个类,然后自动的就被放置在IOC容器中了。注意我们的Person类上 就不需要任何的注解了,直接导入即可。
3.2 @Import + ImportSelector
其实在
@Import
注解的源码中,说的已经很清楚了,感兴趣的可以看下,我们实现一个ImportSelector
的接口,然后实现其中的方法,进行导入。代码如下:
@Import(MyImportSelector.class)
publicclassDemo1{
publicstaticvoidmain(String[] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
}
}
classMyImportSelectorimplementsImportSelector{
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
returnnew String[]{"com.springboot.pojo.Person"};
}
}
我自定义了一个
MyImportSelector
实现了ImportSelector
接口,重写selectImports
方法,然后将我们要导入的类的全限定名写在里面即可,实现起来也是非常简单。3.3 @Import + ImportBeanDefinitionRegistrar
这种方式也需要我们实现
ImportBeanDefinitionRegistrar
接口中的方法,具体代码如下:@Import(MyImportBeanDefinitionRegistrar.class)
publicclassDemo1{
publicstaticvoidmain(String[] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
}
}
classMyImportBeanDefinitionRegistrarimplementsImportBeanDefinitionRegistrar{
@Override
publicvoidregisterBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry){
// 构建一个beanDefinition, 关于beanDefinition我后续会介绍,可以简单理解为bean的定义.
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();
// 将beanDefinition注册到Ioc容器中.
registry.registerBeanDefinition("person", beanDefinition);
}
}
上述实现其实和Import的第二种方式差不多,都需要去实现接口,然后进行导入。接触到了一个新的概念,
BeanDefinition
,可以简单理解为bean的定义(bean的元数据),也是需要放在IOC容器中进行管理的,先有bean的元数据,applicationContext
再根据bean的元数据去创建Bean。3.4 @Import + DeferredImportSelector
这种方式也需要我们进行实现接口,其实它和
@Import
的第二种方式差不多,DeferredImportSelector
它是ImportSelector
的子接口,所以实现的方法和第二种无异。只是Spring的处理方式不同,它和Spring Boot中的自动导入配置文件 延迟导入有关,非常重要。使用方式如下:@Import(MyDeferredImportSelector.class)
publicclassDemo1{
publicstaticvoidmain(String[] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
}
}
classMyDeferredImportSelectorimplementsDeferredImportSelector{
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
// 也是直接将Person的全限定名放进去
returnnew String[]{Person.class.getName()};
}
}
关于
@Import
注解的使用方式,大概就以上三种,当然它还可以搭配@Configuration
注解使用,用于导入一个配置类。4、使用FactoryBean接口
FactoryBean
接口和BeanFactory
千万不要弄混了,从名字其实可以大概的区分开,FactoryBean
, 后缀为bean,那么它其实就是一个bean,BeanFactory
,顾名思义 bean工厂,它是IOC容器的顶级接口,这俩接口都很重要。代码示例:
@Configuration
publicclassDemo1{
@Bean
public PersonFactoryBean personFactoryBean(){
returnnew PersonFactoryBean();
}
publicstaticvoidmain(String[] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
}
}
classPersonFactoryBeanimplementsFactoryBean<Person> {
/**
* 直接new出来Person进行返回.
*/
@Override
public Person getObject()throws Exception {
returnnew Person();
}
/**
* 指定返回bean的类型.
*/
@Override
public Class<?> getObjectType() {
return Person.class;
}
}
上述代码,我使用
@Configuration + @Bean
的方式将PersonFactoryBean
加入到容器中,注意,我没有向容器中注入 Person, 而是直接注入的PersonFactoryBean
然后从容器中拿Person这个类型的bean,成功运行。5、使用 BeanDefinitionRegistryPostProcessor
其实这种方式也是利用到了
BeanDefinitionRegistry
,在Spring容器启动的时候会执行BeanDefinitionRegistryPostProcessor
的postProcessBeanDefinitionRegistry
方法,大概意思就是等beanDefinition
加载完毕之后,对beanDefinition
进行后置处理,可以在此进行调整IOC容器中的beanDefinition
,从而干扰到后面进行初始化bean。具体代码如下:
publicclassDemo1{
publicstaticvoidmain(String[] args){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
MyBeanDefinitionRegistryPostProcessor beanDefinitionRegistryPostProcessor = new MyBeanDefinitionRegistryPostProcessor();
applicationContext.addBeanFactoryPostProcessor(beanDefinitionRegistryPostProcessor);
applicationContext.refresh();
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);
}
}
classMyBeanDefinitionRegistryPostProcessorimplementsBeanDefinitionRegistryPostProcessor{
@Override
publicvoidpostProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)throws BeansException {
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();
registry.registerBeanDefinition("person", beanDefinition);
}
@Override
publicvoidpostProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)throws BeansException {
}
}
上述代码中,我们手动向
beanDefinitionRegistry
中注册了person的BeanDefinition
。最终成功将person加入到applicationContext
中,上述的几种方式的具体原理,我后面会进行介绍。小结
向spring容器中加入bean的几种方式.
@Configuration + @Bean
@ComponentScan + @Component
@Import
配合接口进行导入使用 FactoryBean
。实现 BeanDefinitionRegistryPostProcessor
进行后置处理。
在 GitHub猿 还有更多优质项目系统学习资源,欢迎分享给其他同学吧!
最后,整理了400多套项目,赠送读者。扫码下方二维码,后台回复【赚钱】即可获取。
--END--
来源:blog.csdn.net/weixin_43741092/article/details/120176466版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢!
往期惊喜:
扫码关注我们的Java架构师技术
带你全面深入Java
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。