Spring source code--Bean life cycle


First come a life cycle diagram of a bean

github address:

https://github.com/a18792721831/studySpringSource.git

BeanNameAware

The structure diagram of BeanNameAware is very simple

image-20200829134754413

Among them, Aware is a marked interface, and there are no internal methods defined:

image-20200829134850253

It can be seen through its comments

image-20200829134952050

BeanNameAwareThe interface has only one method: setBeanNameset the name of the bean.

image-20200829135326711

To be honest, I was confused about this method at first. What use is this method?

Judging from the name and comments, it seems that the name of the bean is set.

But if you think about it carefully, it’s not right. Set the name, it should not beThe parameter is empty, the return value is String, So we can set the name to BeanFactory.

But this method is just the opposite.

Then think in reverse thinking:This method is not to set the name of the bean, but to get the name of the bean.

Combining the design philosophy of spring: ordinary beans are unaware of beanFactory, that is to say, as an ordinary bean, I don't know who will rely on me, and I won't know who manages me. I am an ordinary bean.

In other words, as an ordinary animal, as long as there is work to do, it is enough to move bricks. No matter who he moves the bricks to and what he does.

But if you can't be a social animal for a lifetime, people still have to have ideals.

As a bean, if you want to know your name or code name in the beanFactory, you need to implement BeanNameAwarethe interface, which shows that this bean is not a salty fish, but an ideal and aspiring bean. He wants to know that he is in The name in beanFactory does not want to be a nameless person.

Then when the spring container starts, it finds that there is an ambitious bean, and it kindly setBeanNametells the bean the name of the bean in the beanFactory through methods.

In summary: this method is for the bean to obtain its name in the beanFactory.

BeanFactoryAware

BeanFactoryAwareAnd BeanNameAwaresimilar, the structure is very simple, both inherit the marked interface: Awareinterface, and then implement a method:

image-20200829140559564

If you understand the BeanNameAwaremethod of the interface, then this method is also very easy to understand.

As a bean, if you want to know which beanFactory you are in, you need to implement this interface, and then the container will tell the bean the BeanFactory of the beanFactory where the bean is located.

For example, in order to distinguish the business more clearly, some companies will split the original complete company into multiple subsidiaries, each of which is responsible for a part of the specific business. There are still so many people in the original company, and even the office positions have not changed, but they belong to a different company. If an employee wants to know which branch he belongs to after the split, he needs to send an email to ask human resources.

setBeanFactoryIt is human resources that the beanFactory where the bean is located is returned to the bean.

So far, this bean has been significantly different from other beans. This bean already knows who it is and where it is.

Is it still a salted fish?

ApplicationContextAware

Three very famous questions: who are you, where are you, where are you from?

After talking about the first two steps, the bean brother already knows who he is and where he is. Then, there is one question left, which is the meaning of bean existence and where it comes from.

ApplicationContextIt is the scope of bean life, so if you clearly recognize the scope of your life, you will understand the meaning of your own existence.

image-20200829145234557

ApplicationContextAwareThe method is to tell the bean the context of the runtime.

postProcessBeforeInitialization

The pre-initialization operation takes effect for all beans.

image-20200829145910153

It can be achieved by stealing beams and changing posts. Replace one of the default beans with other beans, and focus on the final return result.

@PostConstruct

Starting from the Java EE5 specification, two annotations that affect the life cycle of Servlet have been added to Servlet, @PostConstruct and @PreDestroy, these two annotations are used to decorate a non-static void() method.

image-20200829150557581

afterPropertiesSet

The InitializingBean interface provides a way for the bean to initialize. It only includes the afterPropertiesSet method. Any class that inherits this interface will execute this method when the bean is initialized.

How are the methods of this interface called?

Let's search it all:instanceof InitializingBean

Insert picture description here

If init-method and afterPropertiesSet are configured at the same time, execute the afterPropertiesSet method first, and then execute init-method.

postProcessAfterInitialization

The pre-initialization operation takes effect for all beans.

Insert picture description here

@PreDestory

Starting from the Java EE5 specification, two annotations that affect the life cycle of Servlet have been added to Servlet, @PostConstruct and @PreDestroy, these two annotations are used to decorate a non-static void() method.

image-20200829152019234

DisposableBean

For a bean that implements DisposableBean, call its destroy() method after spring releases the bean.

image-20200829152439912

Instance

Create a bean

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author jiayq
 * @Date 2020-08-29
 */
@Component
public class People implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, BeanPostProcessor, InitializingBean, DisposableBean {
    
    

    public People() {
    
    
        System.out.println("1.create");
    }

    @Override
    public void setBeanName(String name) {
    
    
        System.out.println("2.set bean name : " + name);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
    
    
        System.out.println("3.set bean factory , name is " + beanFactory.getClass().getSimpleName());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        System.out.println("4.set application context , name is " + applicationContext.getClass().getSimpleName() + " , id is " + applicationContext.getId());
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    
    
        System.out.println("5.post process before initialization , bean name is " + beanName);
        return bean;
    }

    @PostConstruct
    public void init() {
    
    
        System.out.println("6.post construct , this name is " + this.getClass().getSimpleName());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
    
    
        System.out.println("7.after properties set ");
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    
    
        System.out.println("8.post process after initializattion , bean name is " + beanName);
        return bean;
    }

    public void say() {
    
    
        System.out.println("9.normal survival");
    }

    @PreDestroy
    public void destory() {
    
    
        System.out.println("10.pre destory");
    }

    @Override
    public void destroy() throws Exception {
    
    
        System.out.println("11.destroy by DisposableBean");
    }
}

main class


import com.study.source.beans.People;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

@SpringBootApplication
public class SourceApplication {
    
    

    public static void main(String[] args) {
    
    
//        ConfigurableApplicationContext context = SpringApplication.run(SourceApplication.class, args);
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.study.source");
        People bean = context.getBean(People.class);
        bean.say();
        context.close();
    }
}

Output result:

image-20200829152730962

image-20200829152811633

View AnnotationConfigApplicationContextthe call chain under

image-20200829153038102

The refresh is the core content of spring

Insert picture description here

Guess you like

Origin blog.csdn.net/a18792721831/article/details/108295349