What are the spring IOC features? I can't understand the source code!

Little brother Fu 2021-04-08 09:48:00
spring ioc features understand source



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 about ass Wai GA Bu, just say 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 Bean: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 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 Bean:org.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 Bean:org.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 Bean:org.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 Bean:org.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 Bean:org.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 Bean:org.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

版权声明
本文为[Little brother Fu]所创,转载请带上原文链接,感谢
https://javamana.com/2021/04/20210408093319844i.html

  1. How to realize encryption and decryption of spring boot interface parameters gracefully?
  2. A new way to play in spring 5! This kind of URL request makes me see better!
  3. Can parameters in spring MVC be passed like this? It's up!
  4. Hand in hand to teach you how to develop mybatis plug-ins
  5. Fine spring boot + thymeleaf, there are so many fun details!
  6. Spring boot logs all kinds of posture, it's time to clear!
  7. Web 3.0踏浪而来,分布式存储举足轻重|时空云邀请您参加Web3.0中国峰会暨分布式存储行业大会
  8. spring-aop 进不了切面方法的解决办法
  9. 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
  10. The solution of spring AOP can't enter the section method
  11. Linux中如何启用root用户
  12. How to enable root in Linux
  13. 踩坑 MySQL 索引,看看你真的会用吗?
  14. Hive优化之配置参数的优化(一)
  15. Step on the MySQL index to see if you really know how to use it?
  16. Optimization of configuration parameters for hive optimization (1)
  17. Linux入门教程资料分享
  18. Introduction to Linux
  19. 外部连接mysql docker容器异常
  20. Exception of external connection MySQL docker container
  21. Zookeeper分布式锁?
  22. Zookeeper distributed lock?
  23. 嵌入式Linux_Framebuffer_03点阵显示ASCII字符串
  24. 嵌入式Linux_Framebuffer_02字符编码
  25. Embedded Linux_ Framebuffer_ 03 dot matrix display ascii string
  26. Embedded Linux_ Framebuffer_ 02 character encoding
  27. Looking forward to new product launch of Xiaomi in spring CNMO takes you to see 11 new products in advance
  28. An inventory of the commonly used garbage collectors in Java
  29. Why is it so easy to get started with HBase?
  30. Implementation of PRC framework based on netty
  31. 2021 Java back end engineer must know knowledge - (Dubbo, distributed RPC framework)
  32. 关于spring advisor和元数据 同时来管理事务的问题
  33. How to manage transactions with spring advisor and metadata at the same time
  34. 使用Playwright对Java API实现自动视觉测试 - applitools
  35. Using playwright to implement automatic visual testing for Java API - applitools
  36. Dubbo和Spring cloud、Istio对比图
  37. Comparison of Dubbo with spring cloud and istio
  38. HttpServletRequest、通过request获得请求头、请求体等、解决中文乱码等问题
  39. Mybatis学习笔记-一对一,一对多,多对多关联查询
  40. Mybatis学习笔记-基本概念与操作
  41. HttpServletRequest, obtaining request header and request body through request, solving Chinese garbled code and other problems
  42. Mybatis learning notes - one to one, one to many, many to many association query
  43. Mybatis learning notes - basic concepts and operation
  44. Spring Cloud 升级之路 - 2020.0.x - 3. Undertow 的 accesslog 配置
  45. Spring cloud upgrade road - 2020.0. X - 3. Accesslog configuration of undertow
  46. 被Java培训机构坑骗后,我在这里找回了自信
  47. After being cheated by java training institutions, I found my confidence here
  48. Linux下安装Mysql出现的常见问题以及解决办法
  49. Common problems and solutions of installing MySQL under Linux
  50. java并发编程JUC第十二篇:AtomicInteger原子整型
  51. Java Concurrent Programming JUC Chapter 12: atomicinteger atomic integer
  52. 面经手册 · 第29篇《Spring IOC 特性有哪些,不会读不懂源码!》
  53. Chapter 29 "what are the features of spring IOC? I can't understand the source code! 》
  54. 浅析linux容器--Docker
  55. Analysis of Linux container -- docker
  56. 换种方法学操作系统,轻松入门Linux内核
  57. 浅析linux容器--Docker
  58. Another way to learn operating system, easy access to Linux kernel
  59. Analysis of Linux container -- docker
  60. 手摸手教你阅读和调试大型开源项目 ZooKeeper