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

Spring IOC What are the features , Can not read the source code ! More articles about

  1. read Zepto Source set operation

    The next few chapters , Will interpret zepto The heel in dom Related methods , That's the source code $.fn Methods in objects . read Zepto The source code series has been put in github On , welcome star: reading-zepto Source code ...

  2. read Zepto Source series

    Although I haven't used it in my work recently zepto , But it is said that zepto The source code is relatively simple , And there's a lot of information on the Internet , So I chose zepto Lay hands on , Hope to lay a foundation for reading the source code of other frameworks in the future . Source version The source of this article is ...

  3. 【 read fastclick Source code feeling 】 Thorough solution tap“ Point through ”, Improve the click response speed of mobile terminal

    Affirming !!! It turns out that the judgment is wrong , Just read it , Under study ..... Nima, the water is too deep Preface The recent use tap The incident brought me such and such problems , One of the problems is that we need to change the original one by one click Turn into tap, In this case ...

  4. read jQuery Source code - Deferred

    Deferred First appeared in jQuery 1.5 in , stay jQuery 1.8 And then it was rewritten , Its appearance smoothed out javascript A lot of callbacks in the pyramid , Provides the ability to program asynchronously , It mainly serves jQuery.ajax ...

  5. read Zepto Internal methods of source code

    Array methods Definition var emptyArray = [] concat = emptyArray.concat filter = emptyArray.filter slice = emptyArray ...

  6. read zepto Source of the tool function

    Zepto Provides a wealth of tool functions , Let's read it one by one . Source version The source code of this article is zepto1.2.0 $.extend $.extend Methods can be used to extend the properties of the target object . The property of the target object with the same name is replaced by the property of the source object ...

  7. read Zepto The magic of source code $

    After the foreshadowing of the first three chapters , The play finally wrote about . In use zepto when , You can't do without this amazing $ Symbol , This article will look at zepto How to achieve $ Of . read Zepto The source code series has been put in github On , welcome ...

  8. read Zepto Source set element search

    This one is still with dom Related methods , The focus is on the methods related to the search of set elements . read Zepto The source code series has been put in github On , welcome star: reading-zepto Source version The source code of this article is zept ...

  9. read Zepto Operation of source code DOM

    This one is still with dom Related methods , The emphasis is on operation dom Methods . read Zepto The source code series has been put in github On , welcome star: reading-zepto Source version The source code of this article is zepto1 ...

  10. read Zepto The style operation of source code

    This one is still with dom Related methods , The emphasis is on how to manipulate styles . read Zepto The source code series has been put in github On , welcome star: reading-zepto Source version The source code of this article is zepto1.2. ...

Random recommendation

  1. webApp Development

    1.Viewport: The view screen , The properties that can be manipulated are as follows : width //viewport Width , Range from 200-10000, The default is 980 Pixels height //viewport Height initial-sc ...

  2. 【HNOI2004】【P1365】L Language

    tire Water problem ,%Menci The original title is : Punctuation appears later than words , So the previous languages have no punctuation . Now you have to deal with an article without punctuation . An article T It's made up of a number of lowercase letters . A word W It's also made up of small letters . ...

  3. jQuery.extend Function detailed usage !

    Recent research jQuery. hold jQuery.extend Record the usage of the extension function . 1. Expand jQuery Static methods . }) usage : $.test() 2. Merge multiple objects . by jQuery.extend(css1, ...

  4. SPOJ-ANTP [ Combinatorial mathematics ]

    tags:[ Combine ][ Preprocessing ] Answer key : About the equation A+C+B=X The number of positive integer solutions of . Let's use the board method to know , The number of groups of solutions = stay (X-1) So the answer is :C(x-1,2)+C(x,2)+C(x+1,2)+ ...

  5. Volley, Small concurrent network request a good helper

    Have to say , When you don't know something , You'll think, of course , It's mysterious . But when you really come into contact with these mysterious item, There would be no such feeling . As a android I'm a novice developer , Just came into contact with Volley This open source web request box ...

  6. Click on iframe Hyperlinks in the window , How to open a new page

    Click on iframe The way hyperlinks in windows open new pages : a Set the button click event in the tag , The method called by the event uses the following method to jump to the link :  window.open('url link ', '_blank');

  7. FutureTask Principle analysis

    Link to the original text :http://www.studyshare.cn/blog-front/blog/details/1130 First write a simple Demo public static void main(Stri ...

  8. Day06 ( Hacker Growth Diary ) The role of initial function and return value

    Defined function : 1. Initial recognition function : When we're learning strings , There are operations like this : li = 'tsy be ba bvake ' print(len(li)) This will print out li The length of , We used python Medium len ...

  9. Game hua-rong-dao [NOIP 2013]

    Describltion Small B Recently I fell in love with Hua Rong Dao , But it always takes him a long time to finish it . therefore , He thought of using programming to complete Huarong Road : Given a situation , Is Huarong Road impossible to complete at all , If it can be done , How long does it take at least . Small ...

  10. CentOS7.4 install Java8

    Download from the official website Jdk8Linux64 Bit version : Use MobaXterm Tools connect to remote Linux System : Upload the downloaded file to the remote system /usr/local/ Folder : First enter the directory where the compressed package is located, and then enter the command to unzip it jdk ...