首页
学习
活动
专区
圈层
工具
发布
49 篇文章
1
美团面试:如何设计一个RPC框架?
2
美团面试:如何设计一个注册中心?
3
消息队列设计精要
4
Replication(上):常见的复制模型&分布式系统的挑战
5
Replication(下):事务,一致性与共识
6
网易面试:将Bean放入Spring容器中有几种方式?
7
MySQL慢查询之慢 SQL 定位、日志分析与优化方案
8
面试官:MQ 消息丢失、重复、积压问题,如何解决?
9
面试官:Spring中获取Bean有几种方式?
10
面试:你知道Java性能优化有哪些手段?
11
面试官:千万级数据,怎么快速查询?
12
面试官:你会哪些JVM调优参数?
13
面试官:如何设计一个 订单系统?
14
和面试官聊了半小时的MySQL索引!
15
121道分布式面试题和答案
16
数据库分库分表,何时分?怎样分?
17
一个单例模式,被问7个问题,难!
18
在线面试:如何设计一个秒杀系统?
19
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存?
20
面试官:熟悉SQL优化吗?我只知道20种,其实远不止...
21
吐血整理 | Java并发编程 72 卷
22
面试官再问currentHashMap,就将这篇文章甩给他
23
保姆级教程,2万字详解JVM
24
这代码写的跟狗屎一样!怎么优化?19招搞定它
25
P7大佬压箱底的学习笔记
26
6000多字 | 秒杀系统设计注意点
27
动画+原理+代码+优化,解读十大经典排序算法
28
到底什么是重入锁?拜托,一次搞清楚!
29
面试官再问你 ThreadLocal,你就这样“怼”回去!
30
分布式锁:5个案例,附源码
31
美团面试:说说CAP,我的回答方式很特别
32
分布式事务 :可靠消息最终一致性方案
33
美团面试官:讲清楚MySQL结构体系,立马发offer
34
equals方法比较的是内容?谁告诉你的
35
我通过六个 MySQL 死锁案例,终于理解了死锁的原因
36
必知必会 RabbitMQ面试题 33道(附答案)
37
万字总结 MySQL核心知识,赠送25连环炮
38
那些年,面试被虐过的红黑树
39
小老弟用 案列 引出 ReentrantLock实现原理
40
五分钟说清楚 Spring Boot的自动配置原理
41
面试:Zookeeper常见11个连环炮
42
长文干货 | 手写自定义持久层框架!
43
怒肝一夜 | Mybatis源码深度解析
44
美女面试官问我:能说几个常见的Linux性能调优命令吗?
45
吊打面试官系列:final、finally、finalize 有什么区别?
46
面试官问:如何排除GC引起的CPU飙高?我脱口而出5个步骤
47
JVM真香系列:堆内存详解
48
电商项目实战:如何设计站内信
49
72道 并发编程 面试题!
清单首页面试文章详情

网易面试:将Bean放入Spring容器中有几种方式?

你好,我是田哥

昨天,一位同学去网易面试,回来跟我反馈说被问遇到:将bean放入Spring容器中有哪些方式?这位同学说自己回答了三种,但总感觉自己回答的不太漂亮,下面我就来总结一下。

我们平时在开发中使用Spring的时,都是将Bean交给Spring去管理。

那么将一个对象加入到Spring容器中,有哪些方式呢?

1、@Configuration + @Bean

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

代码语言:javascript
复制
@Configuration
public class MyConfiguration {
    @Bean
    public Person person() {
        Person person = new Person();
        person.setName("spring");
        return person;
    }
}

2、@Componet + @ComponentScan

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

代码语言:javascript
复制
@Component
public class Person {
    private String name;
 
    public String getName() {
 
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public 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);
    }
}

结果输出:

代码语言:javascript
复制
Person{name='null'}

表示成功将Person放置在了IOC容器中。

3、@Import注解导入

前两种方式,大家用的可能比较多,也是平时开发中必须要知道的,@Import注解用的可能不是特别多了,但是也是非常重要的,在进行Spring扩展时经常会用到,它经常搭配自定义注解进行使用,然后往容器中导入一个配置文件。关于@Import注解,我会多介绍一点,它有四种使用方式。这是@Import注解的源码,表示只能放置在类上。

代码语言:javascript
复制
@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直接导入类

代码示例如下:

代码语言:javascript
复制
public class Person {
    private String name;
 
    public String getName() {
 
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public 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的接口,然后实现其中的方法,进行导入。

代码语言:javascript
复制
@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 {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[]{"com.springboot.pojo.Person"};
    }
}

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

3.3 @Import + ImportBeanDefinitionRegistrar

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

代码语言:javascript
复制
@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 {
 
    @Override
    public 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中的自动导入配置文件 延迟导入有关,非常重要。使用方式如下:

代码语言:javascript
复制
@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 {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        // 也是直接将Person的全限定名放进去
        return new String[]{Person.class.getName()};
    }
}

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

4、使用FactoryBean接口

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

代码语言:javascript
复制
@Configuration
public class Demo1 {
    @Bean
    public 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进行返回.
     */
    @Override
    public Person getObject() throws Exception {
        return new Person();
    }
    /**
     *  指定返回bean的类型.
     */
    @Override
    public Class<?> getObjectType() {
        return Person.class;
    }
}

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

5、使用 BeanDefinitionRegistryPostProcessor

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

代码语言:javascript
复制
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 {
 
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.rootBeanDefinition(Person.class).getBeanDefinition();
        registry.registerBeanDefinition("person", beanDefinition);
    }
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
 
    }
}

上述代码中,我们手动向beanDefinitionRegistry中注册了person的BeanDefinition,最终成功将person加入到applicationContext中。

总结

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

  • @Configuration + @Bean
  • @ComponentScan + @Component
  • @Import 配合接口进行导入
  • 使用FactoryBean
  • 实现BeanDefinitionRegistryPostProcessor进行后置处理。
下一篇
举报
领券