欢迎关注方志朋的博客,回复”666“获面试宝典

来源:blog.csdn.net/weixin_43741092/

article/details/120176466

将bean放入Spring容器中有哪些方式?

我们知道平时在开发中使用Spring的时候,都是将对象交由Spring去管理,那么将一个对象加入到Spring容器中,有哪些方式呢,下面我就来总结一下

1、@Configuration + @Bean

这种方式其实,在上一篇文章已经介绍过了,也是我们最常用的一种方式,@Configuration用来声明一个配置类,然后使用 @Bean 注解,用于声明一个bean,将其加入到Spring容器中。

具体代码如下:

@Configuration
public class MyConfiguration {@Beanpublic Person person() {Person person = new Person();person.setName("spring");return person;}
}

2、@Componet + @ComponentScan

这种方式也是我们用的比较多的方式,@Componet中文译为组件,放在类名上面,然后@ComponentScan放置在我们的配置类上,然后可以指定一个路径,进行扫描带有@Componet注解的bean,然后加至容器中。

具体代码如下:

@Component
public class Person {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +'}';}
}@ComponentScan(basePackages = "com.springboot.initbean.*")
public class Demo1 {public static void main(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注解的源码,表示只能放置在类上。

@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直接导入类

代码示例如下:

public class Person {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +'}';}
}
/**
* 直接使用@Import导入person类,然后尝试从applicationContext中取,成功拿到
**/
@Import(Person.class)
public class Demo1 {public static void main(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)
public class Demo1 {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);Person bean = applicationContext.getBean(Person.class);System.out.println(bean);}
}class MyImportSelector implements ImportSelector {@Overridepublic String[] selectImports(AnnotationMetadata importingClassMetadata) {return new String[]{"com.springboot.pojo.Person"};}
}

我自定义了一个 MyImportSelector 实现了 ImportSelector 接口,重写selectImports 方法,然后将我们要导入的类的全限定名写在里面即可,实现起来也是非常简单。

3.3 @Import + ImportBeanDefinitionRegistrar

这种方式也需要我们实现 ImportBeanDefinitionRegistrar 接口中的方法,具体代码如下:

@Import(MyImportBeanDefinitionRegistrar.class)
public class Demo1 {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);Person bean = applicationContext.getBean(Person.class);System.out.println(bean);}
}class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {@Overridepublic void registerBeanDefinitions(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)
public class Demo1 {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);Person bean = applicationContext.getBean(Person.class);System.out.println(bean);}
}
class MyDeferredImportSelector implements DeferredImportSelector {@Overridepublic String[] selectImports(AnnotationMetadata importingClassMetadata) {// 也是直接将Person的全限定名放进去return new String[]{Person.class.getName()};}
}

关于@Import注解的使用方式,大概就以上三种,当然它还可以搭配@Configuration注解使用,用于导入一个配置类。

4、使用FactoryBean接口

FactoryBean接口和BeanFactory千万不要弄混了,从名字其实可以大概的区分开,FactoryBean, 后缀为bean,那么它其实就是一个bean, BeanFactory,顾名思义 bean工厂,它是IOC容器的顶级接口,这俩接口都很重要。

代码示例:

@Configuration
public class Demo1 {@Beanpublic PersonFactoryBean personFactoryBean() {return new PersonFactoryBean();}public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Demo1.class);Person bean = applicationContext.getBean(Person.class);System.out.println(bean);}
}class PersonFactoryBean implements FactoryBean<Person> {/***  直接new出来Person进行返回.*/@Overridepublic Person getObject() throws Exception {return new Person();}/***  指定返回bean的类型.*/@Overridepublic Class<?> getObjectType() {return Person.class;}
}

上述代码,我使用@Configuration + @Bean的方式将 PersonFactoryBean 加入到容器中,注意,我没有向容器中注入 Person, 而是直接注入的 PersonFactoryBean 然后从容器中拿Person这个类型的bean,成功运行。

5、使用 BeanDefinitionRegistryPostProcessor

其实这种方式也是利用到了 BeanDefinitionRegistry,在Spring容器启动的时候会执行 BeanDefinitionRegistryPostProcessor 的 postProcessBeanDefinitionRegistry 方法,大概意思就是等beanDefinition加载完毕之后,对beanDefinition进行后置处理,可以在此进行调整IOC容器中的beanDefinition,从而干扰到后面进行初始化bean。

具体代码如下:

public class Demo1 {public static void main(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);}
}class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {@Overridepublic void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();registry.registerBeanDefinition("person", beanDefinition);}@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {}
}

上述代码中,我们手动向beanDefinitionRegistry中注册了person的BeanDefinition。最终成功将person加入到applicationContext中,上述的几种方式的具体原理,我后面会进行介绍。

小结

向spring容器中加入bean的几种方式:

  • @Configuration + @Bean

  • @ComponentScan + @Component

  • @Import 配合接口进行导入

  • 使用FactoryBean。

  • 实现BeanDefinitionRegistryPostProcessor进行后置处理。

热门内容:
  • 离开互联网上岸1年后,我后悔了!重回大厂内卷

  • 逃过大厂“开猿节流”,斩获12家offer,最牛笔记曝光!

  • IntelliJ IDEA 居然支持音视频聊天!

  • RedisJson 横空出世,性能碾压ES和Mongo!

  • IDEA牛逼!900行"又臭又长"的类重构,几分钟搞定

最近面试BAT,整理一份面试资料《Java面试BAT通关手册》,覆盖了Java核心技术、JVM、Java并发、SSM、微服务、数据库、数据结构等等。
获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。

明天见(。・ω・。)ノ♡

将Bean放入Spring容器中的五种方式相关推荐

  1. SpringBoot教程(十一)——将Bean放入Spring容器中的五种方式

    将bean放入Spring容器中有哪些方式? 我们知道平时在开发中使用Spring的时候,都是将对象交由Spring去管理,那么将一个对象加入到Spring容器中,有哪些方式呢,下面我就来总结一下 1 ...

  2. 将 Bean 放入 Spring 容器中的方式

    文章目录 将 Bean 放入 Spring 容器中的方式 1.@Configuration + @Bean 2.@Componet + @ComponentScan 3.@Import注解导入 3.1 ...

  3. Bean放入Spring容器,你知道几种方式?

    作者:三尺微命  一介书生 来源:blog.csdn.net/weixin_43741092/article/details/120176466 我们知道平时在开发中使用Spring的时候,都是将对象 ...

  4. Spring中把一个bean对象交给Spring容器管理的三种方式

    一.使用@Component,把bean对象依赖交给Spring容器 注意,该注解不能使用,则说明未添加依赖,需要去该项目pom.xml文件内引入依赖,若该项目只是作为一个存放工具类的子模块项目,没有 ...

  5. Spring事务配置的五种方式 说明

    Spring事务配置的五种方式  [转 http://blog.csdn.net/hjm4702192/article/details/17277669] Spring配置文件中关于事务配置总是由三个 ...

  6. Spring事务配置的五种方式和spring里面事务的传播属性和事务隔离级别、不可重复读与幻读的区别

    前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家.点击跳转到教程. spring事务配置的五种方式 前段时间对Spring的事务配置做了比较深入的研究,在此之间对Spr ...

  7. 如何把对象放入spring容器

    在我们开发中,很常见的会遇见我们自己的对象依赖于Spring容器中的对象,此时需要将我们的对象托管给Spring容器,否则我们将无法使用依赖的对象. 下面介绍一下将我们的对象托管给Spring容器的三 ...

  8. SSH深度历险(六) 深入浅出----- Spring事务配置的五种方式

    这对时间在学习SSH中Spring架构,Spring的事务配置做了具体总结.在此之间对Spring的事务配置仅仅是停留在听说的阶段,总结一下.总体把控.通过这次的学习发觉Spring的事务配置仅仅要把 ...

  9. Spring配置事务的五种方式

    Java事务的类型有三种: JDBC事务. 可以将多个 SQL 语句结合到一个事务中.JDBC 事务的一个缺点是事务的范围局限于一个数据库连接.一个 JDBC 事务不能跨越多个数据库 JTA(Java ...

最新文章

  1. 自己动手写C语言编译器(暂停)
  2. mysql Table 'plugin' already exists
  3. Python2.7基础知识点思维导图
  4. Java easycms 版本2.0发布
  5. [译] 虚拟现实是如何改变用户体验的:从原型到设备的设计
  6. Graft货币(GRFT)结点搭建
  7. FaceBook ATC 弱网测试工具环境搭建
  8. ai 数据模型 下载_为什么需要将AI模型像数据一样对待
  9. JDK下载安装及环境变量配置的图文教程(详解)
  10. Python爬虫之scrapy分布式爬虫
  11. 太阳能逐日自动跟踪系统实训装置QY-T28
  12. Linux 下du命令详解及代码实现
  13. 火萤视频壁纸(让你的桌面丰富多彩)
  14. 高位在前低位在后是啥意思_详解MACD指标的死叉卖点:低位死叉+高位死叉+零轴附近死叉...
  15. 记录一下申请邓白氏编码的完整流程
  16. git 拉取指定的远程分支(三种方式)
  17. openssl-genras命令简单入门
  18. spark算子详细介绍(v、k-v、vv类型)
  19. vant框架的输入框在IOS上出现输入空格不显示,需要在输入字符才展示问题
  20. 仅3w报价B站up主竟带来1200w播放!品牌高性价比B站投放标杆!

热门文章

  1. Spring Cloud(八)高可用的分布式配置中心 Spring Cloud Config
  2. 开源交互式自动标注工具EISeg
  3. 嵌入式BootLoader技术内幕(三)
  4. Event自定义事件
  5. 分享十款免费数据恢复软件
  6. html标签(2)--有序列表与无序列表
  7. 今天是第一次开博客,for--futurechild!!!
  8. Scratch青少年编程能力等级测试模拟题(三级)
  9. 【组队学习】【28期】Datawhale组队学习内容介绍
  10. 股市币市:数据分析与交易所最新公告