One 、 Preface
- Springboot Source code analysis is a big project , Study the code line by line , It's going to be boring , It's not easy to stick to it .
- We don't want to be big and complete , But try to study a little knowledge point at a time , Finally, the sand becomes a tower , This is our springboot A glimpse of the source code series .
Two 、ApplicationContextAware
- Suppose we want to use a bean, If it's in @Component Under class , Direct use @Autowired Just quote
- Suppose we want to use... In a static method , You can't use the above method
- You may want to use new Bean() The way ,new One , But this bean Inside @Autowired Citation doesn't work
- If there is a static global ApplicationContext Just fine , use spring Ability acquisition bean: ApplicationContext.getBean(clazz)
- ApplicationContextAware That's the use
public interface ApplicationContextAware extends Aware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
public interface Aware {
}
Let's write an implementation class :
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
private static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}
}
- adopt setApplicationContext, hold applicationContext Assign to a local static variable
- adopt ApplicationContext Of getBean You can use any bean The ability to
3、 ... and 、 Source code analysis
We enter SpringApplication Of run Method :
public ConfigurableApplicationContext run(String... args) {
...
try {
...
refreshContext(context);
...
}
catch (Throwable ex) {
...
}
...
return context;
}
We enter refreshContext(context) Inside :
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
destroyBeans();
cancelRefresh(ex);
throw ex;
}
finally {
resetCommonCaches();
}
}
}
This refresh yes spring The core method of , It will be used many times in the future , It's too much , We only focus on one method this time :
- prepareBeanFactory(beanFactory);
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
...
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
...
}
}
We see first prepareBeanFactory(beanFactory):
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
...
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
...
}
Let's take a look at this addBeanPostProcessor Method
private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList<>();
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
// Remove from old position, if any
this.beanPostProcessors.remove(beanPostProcessor);
// Track whether it is instantiation/destruction aware
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
// Add to end of list
this.beanPostProcessors.add(beanPostProcessor);
}
- First remove, Again add
- beanPostProcessors Is a thread safe list: CopyOnWriteArrayList
- Let's look down new ApplicationContextAwareProcessor(this), Be careful :this yes ApplicationContext
class ApplicationContextAwareProcessor implements BeanPostProcessor {
private final ConfigurableApplicationContext applicationContext;
private final StringValueResolver embeddedValueResolver;
/**
* Create a new ApplicationContextAwareProcessor for the given context.
*/
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
}
@Override
@Nullable
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)){
return bean;
}
AccessControlContext acc = null;
if (System.getSecurityManager() != null) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareInterfaces(bean);
return null;
}, acc);
}
else {
invokeAwareInterfaces(bean);
}
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
- Construction method , hold applicationContext Set to local variables
- How to implement the interface :postProcessBeforeInitialization, It will be used in callback , It's mainly about checking permissions
- The bottom invokeAwareInterfaces It's a private core callback method , According to different types , There are different callbacks
We see that in addition to ApplicationContextAware, There are others aware, in total 6 individual
- EnvironmentAware: environment variable
- EmbeddedValueResolverAware: Value resolver
- ResourceLoaderAware: Resource loader
- ApplicationEventPublisherAware: Event publisher
- MessageSourceAware: Information processor
- ApplicationContextAware:spring Containers
For example, we want to use global environment variables , There is EnvironmentAware, Want to use spring I'll use it when I'm in trouble ApplicationEventPublisherAware, wait
- The source has been found ,ApplicationContextAwareProcessor When was it executed ?
- This is more troublesome , Let's just open a section later and see it in detail .
Welcome to WeChat official account. : Fengji , More technology learning sharing .
springboot The source code parsing - A glimpse of the leopard series aware( 6、 ... and ) More articles about
- SpringBoot Source code analysis series summary
believe me , You will collect this article This article is rolled out in this period of time SpringBoot Source code analysis series of articles summary , When you use SpringBoot Not just for basic use . Or go out for an interview and be abused by the interviewer . Or want to know more about ...
- 【spring-boot The source code parsing 】spring-boot Dependency management chart
In the article [spring-boot The source code parsing ]spring-boot Dependency management in , I combed spring-boot-build.spring-boot-parent.spring-boot-depen ...
- SpringBoot The source code parsing ( Nine )----- Spring Boot The core competencies of - Integrate Mybatis
In this article, we are SpringBoot The integration of Mybatis This orm frame , After all, analyze the source code of its automatic configuration , Let's go back to the past Spring How to integrate Mybatis Of , You can take a look at my article Mybaits Source code ...
- SpringBoot The source code parsing ( Two )----- Spring Boot quintessence : Start process source code analysis
This article looks at it from the perspective of source code Spring Boot What's the start-up process like , Why can the complicated configuration be so simple now . Entrance class @SpringBootApplication public class He ...
- SpringBoot The source code parsing ( 3、 ... and )----- Spring Boot quintessence : Initialize data at startup
We use springboot When building a project , Sometimes there is a need to initialize some operations when the project starts , In response to this demand spring boot For us to provide the following options for us to choose : ApplicationRunn ...
- SpringBoot The source code parsing ( 5、 ... and )----- Spring Boot The core competencies of - Auto configure source code parsing
In the last blog, I analyzed springBoot Start process , The general outline is just the tip of the iceberg . Let's have a look today springBoot The highlight function of : Automatic assembly function . First from @SpringBootApplication Start . At the start of the stream ...
- SpringBoot The source code parsing ( 8、 ... and )----- Spring Boot quintessence : Transaction source code analysis
Let's talk about SpringBoot How to start a transaction automatically , Let's go back to the past SSM How transactions are used in SSM With a transaction Import JDBC Dependency package as everyone knows , All need to deal with the database , Basically, you have to add jdbc Dependence ...
- SpringBoot The source code parsing ( Ten )----- Spring Boot The core competencies of - Integrate AOP
This article mainly integrates Sping An important function AOP Let's go back to the past Spring How to use AOP Of , You can take a look at my article spring5 Source depth analysis ----- AOP The use of and AOP Custom tag Spri ...
- 【spring-boot The source code parsing 】spring-boot Dependency management
key word :spring-boot Dependency management .spring-boot-dependencies.spring-boot-parent problem maven engineering , Dependency management is a very basic and important function , Now the project ...
- SpringBoot The source code parsing ( 6、 ... and )----- Spring Boot The core competencies of - built-in Servlet Container source code analysis (Tomcat)
Spring Boot By default Tomcat As embedded Servlet Containers , Just introduce spring-boot-start-web rely on , The default is Tomcat As Servlet Containers : <depend ...
Random recommendation
- Github Upload your own project
1. Register and create a new project 2. To configure github for windows Preface : Install the corresponding github for windows 2.1 To get the key You can use command mode (Git bash), There is a corresponding usage in resources : ...
- tengine-2.1.0 + GraphicsMagick-1.3.20
export LUAJIT_LIB=/usr/local/libexport LUAJIT_INC=/usr/local/include/luajit-2.0/./configure --prefix ...
- Codeforces 235C
The main idea of the topic : Given a string , Next, I'll give you n A string , Find the number of circular isomorphs of the given string in the original string Build suffix automata from initial string , As we move forward on automata , For example, the current string to be matched is aba, To ...
- java.util.zip.ZipOutputStream Compression without garbled code ( original )
package io; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileI ...
- Hand to hand Windows Next Go Language environment construction
1. Want to write GO The language has to be downloaded first go Language development kit Official download address :https://code.google.com/p/go/downloads/list I use it Win7 64 Bit operating system , The screenshot is as follows : 2. hold ...
- IDL Realization PCA Algorithm
In multivariate statistical analysis , Principal component analysis (Principal components analysis,PCA) It's an analysis . Technology to simplify data sets . Principal component analysis is often used to reduce the dimension of data sets , At the same time, keep the features in the data set that contribute the most to the difference ...
- C++——Vector
#include "opencv2/objdetect.hpp" #include "opencv2/videoio.hpp" #include "o ...
- adb shell Order ----pm
Common usage : View the packages that have been installed : pm list packages Check the installed packages and apk route (-3: Just look at third-party applications : -s: Just look at the system application ) -f: see their associated fi ...
- ( Webpage )Java What programmers most often do 10 A mistake ( turn )
from CSDN: 1. Convert an array to a list When converting an array to a list , Programmers often do this : List<String> list = Arrays.asList(arr); Arrays.asLis ...
- Codeforces 781D Axel and Marston in Bitland
Topic link :http://codeforces.com/contest/781/problem/D ${F[i][j][k][0,1]}$ It means whether there is a problem from ${i-->j}$ The path to success is gone ${2^{k}} ...