4

Received an interview question from a fan who has worked for 4 years today.

The question is: "What are the ways in Spring to inject beans into the IOC container".

He said that this question was the best answer among all the interview questions, but looking at the interviewer's expression, it didn't seem right.

I asked him how he answered and he said: "Interface injection", "Setter injection", "Constructor injection".

Why not? Let's take a look at the answers of ordinary people and experts.

Ordinary people:

Ok. . . . .

Expert:

Ok, there are 7 ways to inject beans into the IOC container

  1. Use xml to declare the bean definition, the Spring container will load and parse this xml when it starts, and load the bean into the IOC container.
  2. Use the @ComponentScan annotation to scan classes that declare @Controller, @Service, @Repository, @Component annotations.
  3. Using the @Configuration annotation to declare the configuration class, and using the @Bean annotation to implement the Bean definition, this method is actually an evolution of the xml configuration method, and is a milestone for Spring to enter the era of no configuration.
  4. Use the @Import annotation to import configuration classes or ordinary beans
  5. Use the FactoryBean factory bean to dynamically build a Bean instance. The dynamic proxy instance in Spring Cloud OpenFeign is implemented using FactoryBean.
  6. Implement the ImportBeanDefinitionRegistrar interface to dynamically inject Bean instances. This startup annotation in Spring Boot is useful.
  7. Implement the ImportSelector interface and dynamically inject configuration classes or Bean objects in batches, which is useful in the automatic assembly mechanism in Spring Boot.

The above is my understanding of the problem.

Summarize

After working for 4 years, IOC and DI have not figured it out. As an interviewer, I can't put water for you.

This topic is also very meaningful. To solve some practical business problems more elegantly, you must first accumulate enough tools.

Have you ever thought that there are so many ways of bean injection, and there are some ways that you have never heard of?

If you need a master interview document (with a 100,000-word interview document inside Ali) or have any technical interview questions you don't understand and want to consult, you can send a private message [Mic] in the background or leave a message in the comment area.

file

Copyright notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated. Please indicate the source for Mic带你学架构 !
If this article is helpful to you, please help to follow and like, your persistence is the driving force for my continuous creation. Welcome to follow the WeChat public account of the same name to get more technical dry goods!

跟着Mic学架构
810 声望1.1k 粉丝

《Spring Cloud Alibaba 微服务原理与实战》、《Java并发编程深度理解及实战》作者。 咕泡教育联合创始人,12年开发架构经验,对分布式微服务、高并发领域有非常丰富的实战经验。