Spring some summary

Speaking of spring, I think anyone who is doing java will be familiar with it. It should be one of the most frequently used frameworks in development. Both web applications and java applications can be quickly accessed to meet our needs.

The following summary is a personal summary of my recent in-depth study of spring, and I hope to deepen my understanding by writing a blog.

Let's
get started... Sometimes we can't get the beans in the spring container through annotations in go. At this time, we can get the beans through the context, the ApplicationContext. In order to get the context, spring provides the perception interface ApplicationContextAware. As long as you implement it, you can get the context. Spring will execute the setting method of the perception interface after the bean is set. such as

package com.example.demo.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextConfig implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
        System.out.println("set application!");
    }

    public static ApplicationContext getApplictionContext(){
        return context;
    }

    public static <T> T getBean(String beanName, Class<T> clazz){
        return context.getBean(beanName, clazz);
    }
}

The setApplicationContext method will be executed after setting the value of the bean property and before executing the init-method.
You can use this feature to implement the actions to be done after the bean is initialized, such as the following service class. After instantiating the bean, if you want to do some preconditions, you can do it in the following way:

package com.example.demo.service;

import com.example.demo.config.ApplicationContextConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class DemoService {

    @PostConstruct
    public void init(){
        ApplicationContext applictionContext = ApplicationContextConfig.getApplictionContext();
        // 前置动作,比如拿到bean后设置bean的值或者添加缓存等
        System.out.println(applictionContext);
    }
}

It is emphasized here that the setting method of the perception interface is executed before the init-method method. It can be seen from the startup log that the
Insert picture description here
spring summary is to be continued...

Guess you like

Origin blog.csdn.net/huangdi1309/article/details/89511241