Chapter 29 "what are the features of spring IOC? I can't understand the source code! 》

bugstack_ cn 2021-04-08 08:57:27
chapter features spring ioc understand


author : Little brother Fu
Blog :https://bugstack.cn

precipitation 、 Share 、 grow up , Let yourself and others have something to gain !

One 、 Preface

Multithreading 、 lock 、JVM tuning , It's all in the back , How to write code is still a mess ?

Why are these from books 、 Classroom 、 Interview is very important knowledge , But in the actual programming did not improve your coding ability ?

First of all, these knowledge in the actual Internet business development , It's almost uncommon , Almost lock and multithread scenarios , In order to improve the performance, distributed design and implementation are basically adopted . Most of these seemingly technical knowledge are packaged in components that are not business logic functions , And programmers are almost not concerned about when doing business development . So it's almost impossible to improve your coding if you do , Most of the promotion is that you're looking for complexity bug There's a time to help .

It's like Can you write poems and odes with Chinese characters ? understand RGB Can you draw mountains and rivers ? If you can jump, you can dance in a swaying posture ? That's impossible , Don't think that you know martial arts !

If you really want to write the code well , Just a little bit from accumulating data structure and algorithm logic ( It's not just a mechanical brush . You don't understand why , No matter how much you brush, it's just in vain ), The next step is to understand design patterns and architecture design , Finally, it's continuous application and summary . In the process, you will be exposed to the business 、 product 、 operating , Coding is just the final implementation , It's not the most important part of the whole process , More important than coding is logic design .

Two 、 Interview questions

Thank you plane , Notes !, This time, the holiday is over and over again Spring, Hey , Go to the test results interview !

interviewer : The plane , What are you going to do today , Have you learned everything I asked you last time ?

Thank you plane :@Resource yes JDK javax.annotation.Resource Notes provided , Ha ha ha ha ha ha ha , In addition, I also learned Bean The injection of .

interviewer : It's good. I remember some , So you're doing Bean When it comes to learning , I have noticed Spring IOC The characteristics of , What do you use ?

Thank you plane : Um. , be used Bean Configuration of 、BeanDefinitionRegistryPostProcessor Yes Bean The definition of 、 also FactoryBean

interviewer : good , I'll talk to you today ,alias、autowire、depends-on、factory-method、lookup-method etc. , Let's see how they are applied in practice .

3、 ... and 、SpringIOC characteristic

IOC(Inversion of Control), The core idea of control reversal is , The use of resources is not managed by the users themselves , It's left to a third party that doesn't use resources to manage it . The advantage is that resources are centrally managed , Configurable 、 Easy maintenance , At the same time, it also reduces the dependence of both sides and achieves low coupling .

As early as 1988 year ,Ralph E. Johnson & Brian Foote In the paper 《Designing Reusable Classes》

One important characteristic of a framework is that the methods defined by the user to tailor the framework will often be called from within the framework itself, rather than from the user’s application code. The framework often plays the role of the main program in coordinating and sequencing application activity. This inversion of control gives frameworks the power to serve as extensible skeletons. The methods supplied by the user tailor the generic algorithms defined in the framework for a particular application.

Next, I'd like to introduce you IOC Some of the core features of , Because it's not just an interview , It's also a function class that needs to be used when developing middleware or groupware , It can be summarized as follows :

1. xml To configure

1.1 alias

Test class

public class UserService {
private UserDao userDao;
public UserService() {
System.out.println(" I was initialized ,UserService");
}
// ...get/set
}

xml To configure

<bean id="userService" class="org.itstack.interview.UserService"/>
<!-- Name it -->
<alias name="userService" alias="userService-alias01"/>
<!-- The alias of an alias -->
<alias name="userService-alias01" alias="userService-alias02"/>

unit testing

@Test
public void test_alias() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config-alias.xml");
logger.info(" obtain Bean:{}", beanFactory.getBean("userService"));
logger.info(" obtain Bean By alias :{}", beanFactory.getBean("userService-alias01"));
logger.info(" obtain Bean Alias by alias :{}", beanFactory.getBean("userService-alias02"));
}

test result

23:01:29.872 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Beanorg.itstack.interview.UserService@2a40cd94
23:01:29.872 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userService'
23:01:29.872 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Bean  By alias org.itstack.interview.UserService@2a40cd94
23:01:29.872 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userService'
23:01:29.872 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Bean  Alias by alias org.itstack.interview.UserService@2a40cd94

  • Purpose : For giving Bean names
  • Use : stay xml In the configuration, we can give a Bean Name it , You can also give an alias a new one .

1.2 autowire

Test class

public class UserDao {
public UserDao() {
System.out.println(" I was initialized ,UserDao");
}
}

xml To configure

<bean id="userDao" class="org.itstack.interview.UserDao"/>
<!-- Manually configure dependencies -->
<bean id="userService-by-property" class="org.itstack.interview.UserService">
<property name="userDao" ref="userDao"/>
</bean>
<!-- Automatically configure dependencies -->
<bean id="userService-by-autowire" class="org.itstack.interview.UserService" autowire="byName"/>

unit testing

@Test
public void test_autowire() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config-autowire.xml");
logger.info(" obtain Bean by Manually configure dependencies :{}", beanFactory.getBean("userService-by-property"));
logger.info(" obtain Bean by Automatically configure dependencies :{}", beanFactory.getBean("userService-by-autowire"));
}

test result

23:05:55.501 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Bean by  Manually configure dependencies org.itstack.interview.UserService@679b62af
23:05:55.501 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'userService-by-autowire'
23:05:55.501 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Bean by  Automatically configure dependencies org.itstack.interview.UserService@5cdd8682

  • Purpose :autowire It is used to inject properties in a class into Spring management
  • Use : stay xml Configuration in progress , There are two ways. They are : Manually configure dependencies 、 Automatically configure dependencies , Manual is very common , Automatic configuration is generally more likely to use annotations . In fact, the autowire It has the same function as annotations ,autowire A few options ,byName、byType、constructor etc. .

1.3 factory-method

Test class

public class StaticFactoryBean {
static public UserDao getUserDaoByStatic(){
return new UserDao();
}
}

xml To configure

<bean id="staticFactory-method" class="org.itstack.interview.StaticFactoryBean" factory-method="getUserDaoByStatic"/>

unit testing

@Test
public void test_factory_method() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config-factory-method.xml");
logger.info(" obtain Bean:{}", beanFactory.getBean("staticFactory-method"));
}

test result

23:15:28.950 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Beanorg.itstack.interview.UserDao@588df31b
23:15:28.950 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'staticFactory-bean'

  • Purpose : Factory methods that identify static factories ( The factory method is static )
  • Use : The core is xml Add in configuration factory-method="getUserDaoByStatic", In this way, the instantiation content of the corresponding static method can be called during initialization .

1.4 factory-bean

Test class

public class StaticFactoryBean {
public UserDao getUserDao(){
return new UserDao();
}
}

xml To configure

<bean id="staticFactory" class="org.itstack.interview.StaticFactoryBean"/>
<bean id="staticFactory-bean" factory-bean="staticFactory" factory-method="getUserDao"/>

unit testing

@Test
public void test_factory_bean_method() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config-factory-method.xml");
logger.info(" obtain Bean:{}", beanFactory.getBean("staticFactory-bean"));
}

test result

23:15:28.950 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Beanorg.itstack.interview.UserDao@33b37288

  • Purpose :factory-bean, Examples are chemical plants
  • Use :factory-bean、factory-method It needs to be used together ,factory-method="getUserDao" Call the corresponding static method to return the instantiation result .

1.5 depends-on

xml To configure

<bean id="userService" class="org.itstack.interview.UserService" depends-on="userDao"/>
<bean id="userDao" class="org.itstack.interview.UserDao"/>

unit testing

@Test
public void test_depends_on() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config-depends-on.xml");
logger.info(" obtain Bean:{}", beanFactory.getBean(UserService.class, "userService").getUserDao());
}

test result

 I was initialized ,UserDao
 I was initialized ,UserService
23:24:14.678 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Beanorg.itstack.interview.UserDao@45afc369

  • Purpose : Dealing with dependency initialization order
  • Use : If not used depends-on="userDao", Then according to the Spring The first thing to initialize is UserService, You need to use this configuration when you need to handle initialization dependencies .

1.6 lookup-method & ApplicationContextAware

Test class

public class UserDaoProvider implements ApplicationContextAware {
private ApplicationContext applicationContext;
public UserDao getUserDao() {
return applicationContext.getBean("userDao", UserDao.class);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}

xml To configure

<bean id="userDao" class="org.itstack.interview.UserDao" scope="prototype"/>
<bean id="provider" class="org.itstack.interview.UserDaoProvider"/>

unit testing

@Test
public void test_lookup_method() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config-lookup-method.xml");
logger.info(" obtain Bean:{}", beanFactory.getBean(UserDaoProvider.class, "provider").getUserDao());
logger.info(" obtain Bean:{}", beanFactory.getBean(UserDaoProvider.class, "provider").getUserDao());
}

test result

 I was initialized ,UserDao
16:29:25.813 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'userDao'
16:29:25.813 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Beanorg.itstack.interview.UserDao@1188e820
16:29:25.813 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Creating instance of bean 'userDao'
 I was initialized ,UserDao
16:29:25.814 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'userDao'
16:29:25.814 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Beanorg.itstack.interview.UserDao@2f490758

  • Purpose : Get the prototype pattern in singleton , Every time you get it, a new object is generated .
  • Use : In fact, the core is ApplicationContextAware The use of and scope="prototype" To configure ,Spring The internal implementation is to use Cglib Method , Regenerate subclasses , Override the configuration method and return object , Achieve the effect of dynamic change .

2. Interface class

2.1 FactoryBean

Test class

public class MyFactoryBean implements FactoryBean<UserDao> {
@Override
public UserDao getObject() throws Exception {
return new UserDao();
}
@Override
public Class<?> getObjectType() {
return UserDao.class;
}
@Override
public boolean isSingleton() {
return true;
}
}

xml To configure

<bean id="userDao" class="org.itstack.interview.MyFactoryBean"/>

unit testing

@Test
public void test_factory_bean() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config-factory-bean.xml");
logger.info(" obtain Bean:{}", beanFactory.getBean("userDao"));
}

test result

23:36:19.339 [main] INFO org.itstack.interview.test.ApiTest -  obtain  Beanorg.itstack.interview.UserDao@3bd94634

  • Purpose : Used to generate Bean Of Bean, It's called FactoryBean
  • Use : Actually, this is used in the last chapter about Bean How to inject into Spring As mentioned , In some ORM frame 、RPC-Starter And so on .

2.2 BeanPostProcessor

Test class

public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println(" Before initialization :" + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println(" After the initialization :" + beanName);
return bean;
}
}

xml To configure

<bean id="beanPostProcessor" class="org.itstack.interview.MyBeanPostProcessor"/>
<bean id="userDao" class="org.itstack.interview.UserDao"/>

unit testing

@Test
public void test_bean_post_processor() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config-bean-post-processor.xml");
}

test result

 Before initialization userDao
 After the initialization userDao
16:38:32.686 [main] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Finished creating instance of bean 'userDao'

  • Purpose : Get Bean Actions before and after object initialization , Do the corresponding treatment
  • Use :BeanPostProcessor yes Spring Framework extension interface class , Through the implementation of this interface , You can go to Bean Do related actions in the process of instantiation , For example, it will be published to the registration center after interception .AOP It's also operated through BeanPostProcessor and IOC Containers make connections .

2.3 BeanFactoryAware

Test class

public class MyBeanFactoryAware implements BeanFactoryAware {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
}
}

  • Purpose : Used to get the runtime Bean Configuration information
  • Use :BeanFactoryAware You can get beanFactory, That's it bean The context of , At this point, it's very easy for you to get the properties of some objects .

Four 、 summary

  • We have introduced Spring IOC Common configuration features and interfaces , Although you may not use it now xml Configuration object , It's basically annotation . However, behind these annotations, there will still be the corresponding implementation of common core principles , Only by summarizing this part of knowledge and learning the source code , To better understand how annotations are used to handle these configurations .
  • About class use of interfaces ,FactoryBean、BeanPostProcessor、BeanFactoryAware、ApplicationContextAware, In the daily business process development, almost no contact with , But if you want to do some core component design or middleware development , It will be used very often . If you don't know how to use this part of knowledge , You can refer to :《SpringBoot Middleware design and development 》
  • We will introduce some source code learning and application layer processing around these knowledge points ,Bean The creation of 、 Loop dependent three-level cache solution, etc . I also hope you can sum up more in the process of learning 、 reflection 、 Record , Build a complete knowledge stack bit by bit .

5、 ... and 、 Series recommendation

( Please indicate the author and source of this article WeChat official account :bugstack Wormhole stack | author : Little brother Fu

Show Disqus Comments
版权声明
本文为[bugstack_ cn]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210408085629141H.html

  1. Spring Boot 中如何统一 API 接口响应格式?
  2. 深入分析 SpringMVC 参数解析器
  3. SpringBoot 中如何自定义参数解析器?
  4. SpringMVC 初始化流程分析
  5. 如何优雅的实现 Spring Boot 接口参数加密解密?
  6. Spring5 里边的新玩法!这种 URL 请求让我涨见识了!
  7. SpringMVC 中的参数还能这么传递?涨姿势了!
  8. 手把手教你开发 MyBatis 插件
  9. 细品 Spring Boot+Thymeleaf,还有这么多好玩的细节!
  10. Spring Boot 日志各种使用姿势,是时候捋清楚了!
  11. Deep analysis of viewresolver of nine components of spring MVC
  12. In depth analysis of handleradapter of nine components of spring MVC
  13. In depth analysis of handlermapping of nine components of spring MVC
  14. Can spring boot define interface methods to be declared private?
  15. Dispatcherservlet of spring MVC source code analysis
  16. Framework servlet for spring MVC source code analysis
  17. How to unify API response format in spring boot?
  18. In depth analysis of spring MVC parameter parser
  19. How to customize parameter parser in springboot?
  20. Analysis of spring MVC initialization process
  21. How to realize encryption and decryption of spring boot interface parameters gracefully?
  22. A new way to play in spring 5! This kind of URL request makes me see better!
  23. Can parameters in spring MVC be passed like this? It's up!
  24. Hand in hand to teach you how to develop mybatis plug-ins
  25. Fine spring boot + thymeleaf, there are so many fun details!
  26. Spring boot logs all kinds of posture, it's time to clear!
  27. Web 3.0踏浪而来,分布式存储举足轻重|时空云邀请您参加Web3.0中国峰会暨分布式存储行业大会
  28. spring-aop 进不了切面方法的解决办法
  29. Web 3.0 is coming, distributed storage is very important | spatiotemporal cloud invites you to attend Web3.0 China Summit and distributed storage industry conference
  30. The solution of spring AOP can't enter the section method
  31. Linux中如何启用root用户
  32. How to enable root in Linux
  33. 踩坑 MySQL 索引,看看你真的会用吗?
  34. Hive优化之配置参数的优化(一)
  35. Step on the MySQL index to see if you really know how to use it?
  36. Optimization of configuration parameters for hive optimization (1)
  37. Linux入门教程资料分享
  38. Introduction to Linux
  39. 外部连接mysql docker容器异常
  40. Exception of external connection MySQL docker container
  41. Zookeeper分布式锁?
  42. Zookeeper distributed lock?
  43. 嵌入式Linux_Framebuffer_03点阵显示ASCII字符串
  44. 嵌入式Linux_Framebuffer_02字符编码
  45. Embedded Linux_ Framebuffer_ 03 dot matrix display ascii string
  46. Embedded Linux_ Framebuffer_ 02 character encoding
  47. Looking forward to new product launch of Xiaomi in spring CNMO takes you to see 11 new products in advance
  48. An inventory of the commonly used garbage collectors in Java
  49. Why is it so easy to get started with HBase?
  50. Implementation of PRC framework based on netty
  51. 2021 Java back end engineer must know knowledge - (Dubbo, distributed RPC framework)
  52. 关于spring advisor和元数据 同时来管理事务的问题
  53. How to manage transactions with spring advisor and metadata at the same time
  54. 使用Playwright对Java API实现自动视觉测试 - applitools
  55. Using playwright to implement automatic visual testing for Java API - applitools
  56. Dubbo和Spring cloud、Istio对比图
  57. Comparison of Dubbo with spring cloud and istio
  58. HttpServletRequest、通过request获得请求头、请求体等、解决中文乱码等问题
  59. Mybatis学习笔记-一对一,一对多,多对多关联查询
  60. Mybatis学习笔记-基本概念与操作