Spring Boot

Spring Boot

img

img

img

img

img

img

img

img

img

启动流程

SpringApplication 初始化 – 通过springFactoryLoader加载ApplicationLisener 和 ApplicationInitailize

SpringApplication run方法,进行上下文初始化,主要是对context的准备工作

​ 包括:配置文件ymal,properties的加载,Environment环境变量的获取和设置,

​ 初始化Context,并实例化AnnotationBeanDefinitionReader等用于读取Resource,注册为BeanDefinitoin的读取器,将Component注解的类注册为BeanDefinition(主要为Configuraiton),会在InvokeBeanFactoryPostProcessor()方法中进行各种 配置类的解析,注入(@Import注解,@Bean,Component,ComponentScan,Import,ImportResource)

AbstractApplicationContext的refresh()

总览

入口

SpringApplication()

1
2
3
4
5
6
7
8
9
10
11
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 实现ApplicationContextInitializer 可以实现initialize()将Bean注册到SingletonMap
// 实现接口进行初始化,再SpringApplication中设置属性
// 在SpringApplication##run() ### prepareContext()方法中调用
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
// META-INF/spring.factories
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = this.deduceMainApplicationClass();
}

SpringApplication ## run()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
this.configureHeadlessProperty();
SpringApplicationRunListeners listeners = this.getRunListeners(args);
// 发布容器启动事件
listeners.starting();

try {
// 封装args 为 ApplicationArguments
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 准备环境信息
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
Banner printedBanner = this.printBanner(environment);
// 创建ApplicationCOntext
context = this.createApplicationContext();
// initialize方法调用
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 调用 AbstractApplicationCOntext 的 refresh()方法创建容器
this.refreshContext(context);
// spring boot - refresh后的操作
this.afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
// 事件发布
listeners.started(context);
this.callRunners(context, applicationArguments);
} catch (Throwable var9) {
this.handleRunFailure(context, var9, listeners);
throw new IllegalStateException(var9);
}

try {
listeners.running(context);
return context;
} catch (Throwable var8) {
this.handleRunFailure(context, var8, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var8);
}
}

AbstractApplicationContext ## refresh()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);

try {
// 初始化 BeanFactoryPostProcessor
this.postProcessBeanFactory(beanFactory);
// 调用BeanFactoryPostProcessor的方法,初始化BeanDefinition
/*
* 5:调用bean工厂的后置处理器
* 这里将满足条件的Bean变成Bean定义(BeanDefinition)
* 在这里才是真正的去解析类及类中的元素注解
* 例如:@Configuration、@ComponentScan、@Bean等等最后将这些Bean定义放入到BeanDefinitionMap中
* 有因必有果,这里调用了之前创建的创世纪处理器Bean定义(BeanDefinition):ConfigurationClassPostProcessor;即单独调用一次getBean
* 因为ConfigurationClassPostProcessor这个创世纪处理器对象拥有绝对的优先权,创世纪的处理器都没有被创建,那后面还玩个屁
* */
this.invokeBeanFactoryPostProcessors(beanFactory);
//
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
// 非懒加载Bean的创建
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}

this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}

}
}

SpringApplication()

1
2
3
4
5
6
7
8
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 初始化器
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = this.deduceMainApplicationClass();
}

ApplicationContextInitializer

调用实现了ApplicationContextInitializer接口的实现类的initialize方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 1.AbstractApplicationContext 类下防范
## run() ## this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 2. ## prepareContext() ### this.applyInitializers(context);
// 3. ## applyInitializers() ## initializer.initialize(context);
// 4. DelegatingApplicationContextInitializer ## initialize();

public void initialize(ConfigurableApplicationContext context) {
ConfigurableEnvironment environment = context.getEnvironment();
List<Class<?>> initializerClasses = this.getInitializerClasses(environment);
if (!initializerClasses.isEmpty()) {
this.applyInitializerClasses(context, initializerClasses);
}
}
4.

Context模块

ApplicationContext

汇总 - BeanFactory, Resourceloader, Publisher, Environment

即包含 获取Bean,加载spring.factory等文件,BeanDefinition,事件的发布和监听,系统环境变量

image-20230403140959807

AbstractApplicationContext

重点实现类:AbstractApplicationContext

包含Refresh() 等一系列方法的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
public static final String MESSAGE_SOURCE_BEAN_NAME = "messageSource";
public static final String LIFECYCLE_PROCESSOR_BEAN_NAME = "lifecycleProcessor";
public static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "applicationEventMulticaster";
private String id;
private String displayName;
// 用于定义父容器
private ApplicationContext parent;
// 当前容器运行的环境变量 -- 获取配置文件
private ConfigurableEnvironment environment;
private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors;
private long startupDate;
private final AtomicBoolean active;
private final AtomicBoolean closed;
// 容器关闭的线程钩子 - 包含容器关闭的方法 AbstractApplicationContext.this.doClose();
private Thread shutdownHook;
// 注册shutdownHook的锁
private final Object startupShutdownMonitor;

private ResourcePatternResolver resourcePatternResolver;
// 包含的BeanFactory的生命周期
private LifecycleProcessor lifecycleProcessor;
// this.initMessageSource(); -> 初始化国际化信息 (Locale)
private MessageSource messageSource;
// 事件广播器,用于发布事件
private ApplicationEventMulticaster applicationEventMulticaster;
// 事件监听者,遍历发布事件通知
private final Set<ApplicationListener<?>> applicationListeners;
private Set<ApplicationListener<?>> earlyApplicationListeners;
// 事件集合
private Set<ApplicationEvent> earlyApplicationEvents;
image-20230403141946420

LifecycleProcessor

image-20230403142450132

AbstractEnvironment

1
2
3
4
5
6
7
8
9
10
11
public abstract class AbstractEnvironment implements ConfigurableEnvironment {
public static final String IGNORE_GETENV_PROPERTY_NAME = "spring.getenv.ignore";
public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profiles.active";
public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profiles.default";
protected static final String RESERVED_DEFAULT_PROFILE_NAME = "default";
protected final Log logger = LogFactory.getLog(this.getClass());
private final Set<String> activeProfiles = new LinkedHashSet();
private final Set<String> defaultProfiles = new LinkedHashSet(this.getReservedDefaultProfiles());
private final MutablePropertySources propertySources = new MutablePropertySources();
private final ConfigurablePropertyResolver propertyResolver;
}

信息获取

两种:以前和现在

SpringBoot外部化配置相关源码API剖析和扩展 - 简书 (jianshu.com)

img

调用链

SpringApplication

1、run() ## ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);

2、prepareEnvironment() ## listeners.environmentPrepared((ConfigurableEnvironment)environment);

SpringApplicationRunListeners ##

3、environmentPrepared()

1
2
3
4
5
6
7
8
9
void environmentPrepared(ConfigurableEnvironment environment) {
Iterator var2 = this.listeners.iterator();

while(var2.hasNext()) {
SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
listener.environmentPrepared(environment);
}

}

EvenPublishingRunListeners

4、environmentPrepared() ##

1
2
3
public void environmentPrepared(ConfigurableEnvironment environment) {
this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));
}

SimpleApplicationMulticaster

5、multicastEvent() ## multicastEvent() ## invokeListener() ## doInvokeListener()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public void multicastEvent(ApplicationEvent event) {
this.multicastEvent(event, this.resolveDefaultEventType(event));
}

public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
Executor executor = this.getTaskExecutor();
Iterator var5 = this.getApplicationListeners(event, type).iterator();

while(var5.hasNext()) {
ApplicationListener<?> listener = (ApplicationListener)var5.next();
if (executor != null) {
executor.execute(() -> {
this.invokeListener(listener, event);
});
} else {
this.invokeListener(listener, event);
}
}
}
protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
ErrorHandler errorHandler = this.getErrorHandler();
if (errorHandler != null) {
try {
this.doInvokeListener(listener, event);
} catch (Throwable var5) {
errorHandler.handleError(var5);
}
} else {
this.doInvokeListener(listener, event);
}
}

private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
listener.onApplicationEvent(event);
} catch (ClassCastException var6) {
String msg = var6.getMessage();
if (msg != null && !this.matchesClassCastMessage(msg, event.getClass())) {
throw var6;
}

Log logger = LogFactory.getLog(this.getClass());
if (logger.isTraceEnabled()) {
logger.trace("Non-matching event type for listener: " + listener, var6);
}
}

}

ApplicationListener

6、onApplicationEvent()

1
2
3
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E var1);
}

ConfigFileApplicationListener

image-20230416183108300

7、onApplicationEvent() ### onApplicationEnvironmentPreparedEvent() ## ## loadPostProcessors()

#####postProcessEnvironment()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
this.onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent)event);
}

if (event instanceof ApplicationPreparedEvent) {
this.onApplicationPreparedEvent(event);
}
}

// onApplicationEnvironmentPreparedEvent()
private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
List<EnvironmentPostProcessor> postProcessors = this.loadPostProcessors();
postProcessors.add(this);
AnnotationAwareOrderComparator.sort(postProcessors);
Iterator var3 = postProcessors.iterator();

while(var3.hasNext()) {
EnvironmentPostProcessor postProcessor = (EnvironmentPostProcessor)var3.next();
postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());
}

}
/// 加载 EnvironmentPostProcessor的 key -- value
// loadPostProcessors()
List<EnvironmentPostProcessor> loadPostProcessors() {
return SpringFactoriesLoader.loadFactories(EnvironmentPostProcessor.class, this.getClass().getClassLoader());
}
// postProcessEnvironment()
// 添加 PropertySources
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
this.addPropertySources(environment, application.getResourceLoader());
}

// addPropertySources()
protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
RandomValuePropertySource.addToEnvironment(environment);
// 加载 ProperySourceLoader -- Yaml / Properties
(new ConfigFileApplicationListener.Loader(environment, resourceLoader)).load();
}
// Loader()
Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
this.logger = ConfigFileApplicationListener.this.logger;
this.loadDocumentsCache = new HashMap();
this.environment = environment;
this.placeholdersResolver = new PropertySourcesPlaceholdersResolver(this.environment);
this.resourceLoader = (ResourceLoader)(resourceLoader != null ? resourceLoader : new DefaultResourceLoader((ClassLoader)null));
// // 加载 ProperySourceLoader -- Yaml / Properties
this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, this.getClass().getClassLoader());
}

// load()
// load()方法调用 - 直到 loader.load()方法
void load() {
FilteredPropertySource.apply(this.environment, "defaultProperties", ConfigFileApplicationListener.LOAD_FILTERED_PROPERTY, (defaultProperties) -> {
this.profiles = new LinkedList();
this.processedProfiles = new LinkedList();
this.activatedProfiles = false;
this.loaded = new LinkedHashMap();
this.initializeProfiles();

while(!this.profiles.isEmpty()) {
ConfigFileApplicationListener.Profile profile = (ConfigFileApplicationListener.Profile)this.profiles.poll();
if (this.isDefaultProfile(profile)) {
this.addProfileToEnvironment(profile.getName());
}

this.load(profile, this::getPositiveProfileFilter, this.addToLoaded(MutablePropertySources::addLast, false));
this.processedProfiles.add(profile);
}

this.load((ConfigFileApplicationListener.Profile)null, this::getNegativeProfileFilter, this.addToLoaded(MutablePropertySources::addFirst, true));
this.addLoadedPropertySources();
this.applyActiveProfiles(defaultProperties);
});
}
// 。。。。。。。。。。。。。。。。。

PropertySourceLoader

8、List<PropertySource<?>> loaded = loader.load(name, resource);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public interface PropertySourceLoader {
String[] getFileExtensions();

List<PropertySource<?>> load(String name, Resource resource) throws IOException;
}



private List<ConfigFileApplicationListener.Document> loadDocuments(PropertySourceLoader loader, String name, Resource resource) throws IOException {
ConfigFileApplicationListener.DocumentsCacheKey cacheKey = new ConfigFileApplicationListener.DocumentsCacheKey(loader, resource);
List<ConfigFileApplicationListener.Document> documents = (List)this.loadDocumentsCache.get(cacheKey);
if (documents == null) {
List<PropertySource<?>> loaded = loader.load(name, resource);
documents = this.asDocuments(loaded);
this.loadDocumentsCache.put(cacheKey, documents);
}

return documents;
}

Document

1
2
3
4
5
6
7
8
9
10
11
12
13
public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {
// 封装 List<PropertySource<?>>
private static class Document {
private final PropertySource<?> propertySource;
private String[] profiles;
private final Set<ConfigFileApplicationListener.Profile> activeProfiles;
private final Set<ConfigFileApplicationListener.Profile> includeProfiles;
}
private static class Profile {
private final String name;
private final boolean defaultProfile;
}
}

img

img

img

img

img

img

spring boot

EnvironmentPostProcessor

加载 对应的 环境加载机制到类 到 Spring 容器

image-20230723171852456

1
2
3
4
@FunctionalInterface
public interface EnvironmentPostProcessor {
void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application);
}

ConfigFileApplicationListener

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class ConfigFileApplicationListener implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {
private static final String DEFAULT_PROPERTIES = "defaultProperties";
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/*/,file:./config/";
private static final String DEFAULT_NAMES = "application";
private static final Set<String> NO_SEARCH_NAMES = Collections.singleton((Object)null);
private static final Bindable<String[]> STRING_ARRAY = Bindable.of(String[].class);
private static final Bindable<List<String>> STRING_LIST = Bindable.listOf(String.class);
private static final Set<String> LOAD_FILTERED_PROPERTY;
public static final String ACTIVE_PROFILES_PROPERTY = "spring.profiles.active";
public static final String INCLUDE_PROFILES_PROPERTY = "spring.profiles.include";
public static final String CONFIG_NAME_PROPERTY = "spring.config.name";
public static final String CONFIG_LOCATION_PROPERTY = "spring.config.location";
public static final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location";
public static final int DEFAULT_ORDER = -2147483638;
private final DeferredLog logger = new DeferredLog();
private static final Resource[] EMPTY_RESOURCES;
private static final Comparator<File> FILE_COMPARATOR;
private String searchLocations;
private String names;
private int order = -2147483638;


private class Loader {
private final Log logger;
private final ConfigurableEnvironment environment;
private final PropertySourcesPlaceholdersResolver placeholdersResolver;
private final ResourceLoader resourceLoader;
// PropertySourceLoader
private final List<PropertySourceLoader> propertySourceLoaders;
private Deque<ConfigFileApplicationListener.Profile> profiles;
private List<ConfigFileApplicationListener.Profile> processedProfiles;
private boolean activatedProfiles;
private Map<ConfigFileApplicationListener.Profile, MutablePropertySources> loaded;
private Map<ConfigFileApplicationListener.DocumentsCacheKey, List<ConfigFileApplicationListener.Document>> loadDocumentsCache;

Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
this.logger = ConfigFileApplicationListener.this.logger;
this.loadDocumentsCache = new HashMap();
this.environment = environment;
this.placeholdersResolver = new PropertySourcesPlaceholdersResolver(this.environment);
this.resourceLoader = (ResourceLoader)(resourceLoader != null ? resourceLoader : new DefaultResourceLoader((ClassLoader)null));
// SPI 通过SpringFactoriesLoader加载 PropertySourceLoader.class的类
// PropertiesPropertySourceLoader / YamlPropertySourceLoader
this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, this.getClass().getClassLoader());
}
}

image-20230416180842001

1
ConfigurableEnvironment

image-20230416173223790

Spring Boot

RandomValuePropertySource

1
2
3
4
5
public class RandomValuePropertySource extends PropertySource<Random> {
public static final String RANDOM_PROPERTY_SOURCE_NAME = "random";
private static final String PREFIX = "random.";
private static final Log logger = LogFactory.getLog(RandomValuePropertySource.class);
}

Spring Boot 的 PropertySource

FilteredPropertySource

RandomValuePropertySource

ConfigurationPropertySourcesPropertySource

image-20230416173515198

PropertySourceLoader

1
2
3
4
5
6
7
8
9
Loader(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
this.logger = ConfigFileApplicationListener.this.logger;
this.loadDocumentsCache = new HashMap();
this.environment = environment;
this.placeholdersResolver = new PropertySourcesPlaceholdersResolver(this.environment);
this.resourceLoader = (ResourceLoader)(resourceLoader != null ? resourceLoader : new DefaultResourceLoader((ClassLoader)null));
// 通过SPI机制加载 PropertySourceLoader的实现类
this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, this.getClass().getClassLoader());
}
1
2
3
4
5
6
7
8
9
10
11
12
private List<ConfigFileApplicationListener.Document> loadDocuments(PropertySourceLoader loader, String name, Resource resource) throws IOException {
ConfigFileApplicationListener.DocumentsCacheKey cacheKey = new ConfigFileApplicationListener.DocumentsCacheKey(loader, resource);
List<ConfigFileApplicationListener.Document> documents = (List)this.loadDocumentsCache.get(cacheKey);
if (documents == null) {
// 方法调用入库
List<PropertySource<?>> loaded = loader.load(name, resource);
documents = this.asDocuments(loaded);
this.loadDocumentsCache.put(cacheKey, documents);
}

return documents;
}

加载配置文件信息 Ymal, Properties

image-20230403221322756

Resource 和 ResourceLoader

Resource 将硬盘中的资源加载为Resource 流对象,便于容器的使用

1
2
3
4
5
6
Spring中提供了很多Resource接口的实现类。主要有ByteArrayResource, ClassPathResource, DescriptiveResource, FileSystemResource, InputStreamResource, PortletContextResource, ServletContextResource和UrlResource。常用的有:

ClassPathResource:通过 ClassPathResource 以类路径的方式进行访问;
FileSystemResource:通过 FileSystemResource 以文件系统绝对路径的方式进行访问;
ServletContextResource:通过 ServletContextResource 以相对于Web应用根目录的方式进行访问。
UrlResource :通过java.net.URL来访问资源,当然它也支持File格式,如“file:”、“http:”

image-20230403145219276

ResourceLoader接口用来加载Resource资源

1
2
3
public interface ResourceLoader {
Resource getResource(String location);
}

PropertyResolve和PropertySource

image-20230403143713985

ConfigurableEnvironment

image-20230403143445794

image-20230403143531413

GenericApplicationContext

1
2
3
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
private final DefaultListableBeanFactory beanFactory;
}

image-20230403112543262

xml Reader

1
2
3
public class GenericXmlApplicationContext extends GenericApplicationContext {
private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
}

注解 Reader

AnnotationConfigApplicationContext

1
2
3
4
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
private final AnnotatedBeanDefinitionReader reader;
private final ClassPathBeanDefinitionScanner scanner;
}

image-20230401155405556

ResourceLoader

AnnotationConfigApplicationContext

image-20230403105752794

FileSystemXmlApplicationContext

image-20230403110101738

ClassPathXmlApplicationContext

image-20230403110124284

注册BeanDefinition

BeanDefinitionRegistry

注册表,用于注册BeanDefinition

image-20230403203854079

BeanDefinitionReader

接口 - 通过读取XML 和 配置文件Properties

通过类路径获取Resource对象 生成BeanDefinition对象

image-20230403204454935

AbstractBeanDefinitionReader

PropertiesBeanDefinitionReader

XmlBeanDefinitionReader

image-20230403204359601

Reader / Scanner

AnnotatedBeanDefinitionReader

向注册表中注入自动注入所需要的 BeanPostProcessor的BeanDefinition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class AnnotatedBeanDefinitionReader {
// 注册表
private final BeanDefinitionRegistry registry;
private BeanNameGenerator beanNameGenerator;
private ScopeMetadataResolver scopeMetadataResolver;
private ConditionEvaluator conditionEvaluator;

// 该方法会注册很多的RootBeanDefinition进入register注册表
// ConfigurationClassPostProcessor ---import
// AutowiredAnnotationBeanPostProcessor ---autowired
// CommonAnnotationBeanPostProcessor ---resource
// EventListenerMethodProcessor ---事件监听方法
// DefaultEventListenerFactory ---
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
}

备注:ConfigurationClassPostProcessor的注册过程

ClassPathBeanDefinitionScanner

加载主类所在的包以及子包下的Bean,分装为BeanDefinitionHolder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {
// 注册表
private final BeanDefinitionRegistry registry;
private BeanDefinitionDefaults beanDefinitionDefaults;
@Nullable
private String[] autowireCandidatePatterns;
private BeanNameGenerator beanNameGenerator;
private ScopeMetadataResolver scopeMetadataResolver;
private boolean includeAnnotationConfig;

// scan方法调用doscan方法,进行类路径的扫描
public int scan(String... basePackages);
protected Set<BeanDefinitionHolder> doScan(String... basePackages);
}

image-20230403203655701

ConfigurationClassBeanDefinitionReader

加载Configuration类的BeanDefinition

@Enablexxxx内的@Import(xxx.class)注解, 通过xxx的类路径,进行BeanDefinition的注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ConfigurationClassBeanDefinitionReader {
private static final ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
// 注册BeanDefinition
private final BeanDefinitionRegistry registry;
private final SourceExtractor sourceExtractor;
private final ResourceLoader resourceLoader;
private final Environment environment;
private final BeanNameGenerator importBeanNameGenerator;
// Import注解的注册
private final ImportRegistry importRegistry;
private final ConditionEvaluator conditionEvaluator;

// ImportedConfigurationClass
private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass);
// ImportedResources ---
private void loadBeanDefinitionsFromImportedResources(Map<String, Class<? extends BeanDefinitionReader>> importedResources);
//
private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars);

// BeanMethod
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod);
// ConfigurationClass
private void loadBeanDefinitionsForConfigurationClass(ConfigurationClass configClass, ConfigurationClassBeanDefinitionReader.TrackedConditionEvaluator trackedConditionEvaluator);
}

Bean模块 BeanFactory

AbstractBeanFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
// 父容器
private BeanFactory parentBeanFactory;
@Nullable
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
@Nullable
private ClassLoader tempClassLoader;
private boolean cacheBeanMetadata = true;
@Nullable
private BeanExpressionResolver beanExpressionResolver;
// 类型转换
private ConversionService conversionService;
private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet(4);
private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap(4);
@Nullable
private TypeConverter typeConverter;
private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList();
private final List<BeanPostProcessor> beanPostProcessors = new CopyOnWriteArrayList();
private volatile boolean hasInstantiationAwareBeanPostProcessors;
private volatile boolean hasDestructionAwareBeanPostProcessors;
private final Map<String, Scope> scopes = new LinkedHashMap(8);
@Nullable
private SecurityContextProvider securityContextProvider;
private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap(256);
private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap(256));
private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal("Prototype beans currently in creation");

}

image-20230403141331634

AbstractAutowireCapableBeanFactory

image-20230403140342476

实例化Bean的方法调用入口,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
@Nullable
private BeanFactory parentBeanFactory;
@Nullable
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
@Nullable
private ClassLoader tempClassLoader;
private boolean cacheBeanMetadata = true;
@Nullable
private BeanExpressionResolver beanExpressionResolver;
@Nullable
private ConversionService conversionService;
private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet(4);
private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap(4);
@Nullable
private TypeConverter typeConverter;
private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList();
private final List<BeanPostProcessor> beanPostProcessors = new AbstractBeanFactory.BeanPostProcessorCacheAwareList();
@Nullable
private AbstractBeanFactory.BeanPostProcessorCache beanPostProcessorCache;
private final Map<String, Scope> scopes = new LinkedHashMap(8);
@Nullable
private SecurityContextProvider securityContextProvider;
private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap(256);
private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap(256));
private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal("Prototype beans currently in creation");
private ApplicationStartup applicationStartup;

// 创建Bean的实际流程 -- 即Bean的生命周期
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {}

// 内部类持有BeanPostProcessor
static class BeanPostProcessorCache {
final List<InstantiationAwareBeanPostProcessor> instantiationAware = new ArrayList();
final List<SmartInstantiationAwareBeanPostProcessor> smartInstantiationAware = new ArrayList();
final List<DestructionAwareBeanPostProcessor> destructionAware = new ArrayList();
final List<MergedBeanDefinitionPostProcessor> mergedDefinition = new ArrayList();

BeanPostProcessorCache() {
}
}
}s

DefaultListableBeanFactory — 持有

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
@Nullable
private static Class<?> javaxInjectProviderClass;
private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories;
@Nullable
private String serializationId;
private boolean allowBeanDefinitionOverriding = true;
private boolean allowEagerClassLoading = true;
@Nullable
private Comparator<Object> dependencyComparator;
private AutowireCandidateResolver autowireCandidateResolver;
private final Map<Class<?>, Object> resolvableDependencies;

private final Map<String, BeanDefinition> beanDefinitionMap;
private final Map<String, BeanDefinitionHolder> mergedBeanDefinitionHolders;

private final Map<Class<?>, String[]> allBeanNamesByType;
private final Map<Class<?>, String[]> singletonBeanNamesByType;
private volatile List<String> beanDefinitionNames;
private volatile Set<String> manualSingletonNames;
@Nullable
private volatile String[] frozenBeanDefinitionNames;
private volatile boolean configurationFrozen;
}

image-20230403112739812

refresh()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

// Prepare this context for refreshing.
prepareRefresh();

// Tell the subclass to refresh the internal bean factory.
// 通过各种Context(xml,annotation,groovy) ## loadBeanDefinitions()加载BeanDefinition到当前的
//用于记载BeanDefinition
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);

StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();

// 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);
}

// Destroy already created singletons to avoid dangling resources.
destroyBeans();

// Reset 'active' flag.
cancelRefresh(ex);

// Propagate exception to caller.
throw ex;
}

finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
contextRefresh.end();
}
}
}

Bean模块 Bean

BeanFactoryPostProcessor

1
2
3
public interface BeanFactoryPostProcessor {
void postProcessBeanFactory(ConfigurableListableBeanFactory var1) throws BeansException;
}

BeanDefinitionRegistryPostProcessor

1
2
3
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry var1) throws BeansException;
}

ConfigurationClassPostProcessor

ConfigurationClassPostProcessor实例化:

ConfigurationClassPostProcessor原理详解 - 腾讯云开发者社区-腾讯云 (tencent.com)

1
2
3
// 会进行ConfigurationClassPostProcessor的实例化
refresh() ## invokeBeanFactoryPostProcessors(beanFactory);
// 然后进行调用增强

用于BeanDefinition的注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware {
// 用于注册Import,ConfigurationClass等类的BeanDefinition
private ConfigurationClassBeanDefinitionReader reader;

public static final AnnotationBeanNameGenerator IMPORT_BEAN_NAME_GENERATOR = new FullyQualifiedAnnotationBeanNameGenerator();
private static final String IMPORT_REGISTRY_BEAN_NAME = ConfigurationClassPostProcessor.class.getName() + ".importRegistry";
private SourceExtractor sourceExtractor = new PassThroughSourceExtractor();
private ProblemReporter problemReporter = new FailFastProblemReporter();

private Environment environment;
private ResourceLoader resourceLoader = new DefaultResourceLoader();
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();
private boolean setMetadataReaderFactoryCalled = false;
private final Set<Integer> registriesPostProcessed = new HashSet();
private final Set<Integer> factoriesPostProcessed = new HashSet();

private boolean localBeanNameGeneratorSet = false;
private BeanNameGenerator componentScanBeanNameGenerator;
private BeanNameGenerator importBeanNameGenerator;
}

重点:类的初始化位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
SpringBoot启动: // 备注:在spring中的注册原理差不多,区别是创建 AnnotationConfigApplicationContext
// 的位置在
1.SpringApplication##run()
2.run() ## context = this.createApplicationContext();
// 加载AnnotationConfigApplicationContext的Class
3. createApplicationContext() ## Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
// 实例化Context
4.createApplicationContext() ## BeanUtils.instantiateClass(contextClass)
// 构造函数初始化
5.AnnotationConfigServletWebApplicationContext ## AnnotationConfigServletWebApplicationContext();
public AnnotationConfigServletWebApplicationContext() {
this.annotatedClasses = new LinkedHashSet();
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
// 重点 AnnotationConfigUtils
6.AnnotatedBeanDefinitionReader ##
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
// XXXXXX
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
// 在这加入了 ConfigurationClassPostProcessor
7. AnnotationConfigUtils ##
registerAnnotationConfigProcessors(xxx) {
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet(8);
def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
beanDefs.add(registerPostProcessor());
}
// TODO 什么时候实例化
8.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware {
private static final String IMPORT_REGISTRY_BEAN_NAME = ConfigurationClassPostProcessor.class.getName() + ".importRegistry";
private SourceExtractor sourceExtractor = new PassThroughSourceExtractor();
private ProblemReporter problemReporter = new FailFastProblemReporter();
@Nullable
private Environment environment;
private ResourceLoader resourceLoader = new DefaultResourceLoader();
@Nullable
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();
private boolean setMetadataReaderFactoryCalled = false;
private final Set<Integer> registriesPostProcessed = new HashSet();
private final Set<Integer> factoriesPostProcessed = new HashSet();

// *** 加载
private ConfigurationClassBeanDefinitionReader reader;
private boolean localBeanNameGeneratorSet = false;
// 用于创建Bean的名字
private BeanNameGenerator componentScanBeanNameGenerator;
private BeanNameGenerator importBeanNameGenerator;
public static final AnnotationBeanNameGenerator IMPORT_BEAN_NAME_GENERATOR = new FullyQualifiedAnnotationBeanNameGenerator();
}

image-20230403150305959

PropertySource

Bean的属性

bean 的实例过程:

  • ResourceLoader 加载配置信息生成 Resource;
  • BeanDefinitionReader 读取并解析标签,并将标签的属性转换为 BeanDefinition 对应的属性,并注册到 BeanDefinitionRegistry 表中;
  • 容器扫描 BeanDefinitionRegistry 注册表,通过反射机制(具体实现是在refresh方法中的invokeBeanFactoryPostProcessors方法)获取 BeanFactoryPostProcessor 类型的工厂后处理器,并用该处理器对 BeanDefinition 进行加工;
  • 根据处理过的 BeanDefinition,实例化 bean。然后 BeanWrapper 结合 BeanDefinitionRegistry 和 PropertyEditorRegistry 对 bean 的属性赋值。

BeanMetadataElement

不懂嘞

image-20230403200131249

1
2
3
4
5
6
public interface BeanMetadataElement {
@Nullable
default Object getSource() {
return null;
}
}

BeanDefinitionHolder

持有BeanDefinition和他的别名,用于查找BeanDefinition

1
2
3
4
5
6
7
8
9
public class BeanDefinitionHolder implements BeanMetadataElement {
private final BeanDefinition beanDefinition;
private final String beanName;
@Nullable
private final String[] aliases;
public Object getSource() {
return this.beanDefinition.getSource();
}
}

PropertyAccessor

提供对PropertyValue进行get和set的接口,主要由BeanWrapper进行暴露实现。

image-20230403195553426

image-20230403195333627

BeanWrapper

通过操作Propertyvalue对属性进行复制

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface BeanWrapper extends ConfigurablePropertyAccessor {
void setAutoGrowCollectionLimit(int var1);

int getAutoGrowCollectionLimit();

Object getWrappedInstance();

Class<?> getWrappedClass();
// 获取Property
PropertyDescriptor[] getPropertyDescriptors();

PropertyDescriptor getPropertyDescriptor(String var1) throws InvalidPropertyException;
}

创建Bean实例的时候,进行BeanWrapper的初始化和创建

1
2
3
4
5
6
// AbstractBeanFactory ## CreateBean() ##  createBeanInstance()
// 初始化 BeanWrapper
protected void initBeanWrapper(BeanWrapper bw) {
bw.setConversionService(this.getConversionService());
this.registerCustomEditors(bw);
}
ConversionService

转化对象类型

1
2
3
4
5
6
7
8
9
10
11
public interface ConversionService {
boolean canConvert(@Nullable Class<?> var1, Class<?> var2);

boolean canConvert(@Nullable TypeDescriptor var1, TypeDescriptor var2);

@Nullable
<T> T convert(@Nullable Object var1, Class<T> var2);

@Nullable
Object convert(@Nullable Object var1, @Nullable TypeDescriptor var2, TypeDescriptor var3);
}
ConfigurablePropertyAccessor

用于设置BeanWrapper的类型转化对象 ConversionService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface ConfigurablePropertyAccessor extends PropertyAccessor, PropertyEditorRegistry, TypeConverter {
void setConversionService(@Nullable ConversionService var1);

@Nullable
ConversionService getConversionService();

void setExtractOldValueForEditor(boolean var1);

boolean isExtractOldValueForEditor();

void setAutoGrowNestedPaths(boolean var1);

boolean isAutoGrowNestedPaths();
}

image-20230406213250432

image-20230406222830105

AttributeAccessor

关键类:PropertyValue,BeanDefinition

操作bean对象的各种属性

image-20230403195527591

image-20230403195419065

BeanDefinition

AbstarctBeanDefinition
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor implements BeanDefinition, Cloneable {
// 自动注入的方式 -- byName,byType, Constructor
public static final String SCOPE_DEFAULT = "";
public static final int AUTOWIRE_NO = 0;
public static final int AUTOWIRE_BY_NAME = 1;
public static final int AUTOWIRE_BY_TYPE = 2;
public static final int AUTOWIRE_CONSTRUCTOR = 3;
// 通过依赖检查来查看 Bean 的每个属性是否都设置完成
// 以下常量分别对应:不检查、对依赖对象检查、对基本类型,字符串和集合进行检查、对全部属性进行检查
public static final int DEPENDENCY_CHECK_NONE = 0;
public static final int DEPENDENCY_CHECK_OBJECTS = 1;
public static final int DEPENDENCY_CHECK_SIMPLE = 2;
public static final int DEPENDENCY_CHECK_ALL = 3;

// Class对象
private volatile Object beanClass;
// 范围:单例,原型
private String scope;
private boolean abstractFlag;
@Nullable
private Boolean lazyInit;
// 自动注入类型
private int autowireMode;
private int dependencyCheck;
// 依赖
private String[] dependsOn;
private boolean autowireCandidate;
private boolean primary;
// @Qualifier("beanName") -- 当有多个注入对象时,根据 注解指定的beanname进行细致化注解
private final Map<String, AutowireCandidateQualifier> qualifiers;

private Supplier<?> instanceSupplier;
private boolean nonPublicAccessAllowed;
private boolean lenientConstructorResolution;
// beanName
private String factoryBeanName;
// 参数列表
private MutablePropertyValues propertyValues;
// 方法属性/ 名称
private String factoryMethodName;
private ConstructorArgumentValues constructorArgumentValues;
private MethodOverrides methodOverrides;
private String initMethodName;
private String destroyMethodName;

private boolean enforceInitMethod;
private boolean enforceDestroyMethod;

private String description;
private Resource resource;
}
RootBeanDefinition

image-20230403193159013

AnnotatedGenericBeanDefinition

image-20230403193342924

PropertyValue

1
2
3
4
5
6
7
8
9
10
11
public class PropertyValue extends BeanMetadataAttributeAccessor implements Serializable {
private final String name;
@Nullable
private final Object value;
private boolean optional = false;
private boolean converted = false;
@Nullable
private Object convertedValue;
@Nullable
volatile Boolean conversionNecessary;
}

image-20230403194257013

PropertySource

Bean的生命周期

img

createBean()

实例化前

doCreateBean()

实例化

包装类 BeanWrapper 设置

1
doCreateBean()##   this.populateBean(beanName, mbd, instanceWrapper);

populateBean()

实例化后

通过name,type属性填充,

通过postProcess进行PropertyValue属性填充

1
doCreateBean()##   exposedObject = this.initializeBean(beanName, exposedObject, mbd);

初始化前

初始化

初始化后

doGetBean()

Bean生命周期的整个流程 – 处理销毁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException {
String beanName = this.transformedBeanName(name);
Object sharedInstance = this.getSingleton(beanName);
Object beanInstance;
if (sharedInstance != null && args == null) {
// 直接获取实例Bean
beanInstance = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);
} else {
// 尝试父容器 获取Bean
BeanFactory parentBeanFactory = this.getParentBeanFactory();
if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) {
String nameToLookup = this.originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory)parentBeanFactory).doGetBean(nameToLookup, requiredType, args, typeCheckOnly);
}

if (args != null) {
return parentBeanFactory.getBean(nameToLookup, args);
}
if (requiredType != null) {
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
return parentBeanFactory.getBean(nameToLookup);
}

// 标记创建状态
StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate").tag("beanName", name);

try {
if (requiredType != null) {
beanCreation.tag("beanType", requiredType::toString);
}
//
RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
this.checkMergedBeanDefinition(mbd, beanName, args);
String[] dependsOn = mbd.getDependsOn();
String[] var12;
// 依赖对象的注入和实例化
if (dependsOn != null) {
var12 = dependsOn;
int var13 = dependsOn.length;
for(int var14 = 0; var14 < var13; ++var14) {
String dep = var12[var14];
this.registerDependentBean(dep, beanName);
// 获取依赖的Bean对象
this.getBean(dep);
}
// 通过scope来判断如何进行 创建bean createBean()
if (mbd.isSingleton()) {
// 单例对象
// 传入ObejctFactory,用于AOP的代理对象的生成
sharedInstance = this.getSingleton(beanName, () -> {
try {
// createBean
return this.createBean(beanName, mbd, args);
} catch (BeansException var5) {
this.destroySingleton(beanName);
throw var5;
}
});
// 对于 FactoryBean**进行实例替换 -- getOject()
beanInstance = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
// 原型对象创建Bean
Object prototypeInstance;
try {
// this.prototypesCurrentlyInCreation.set(beanNameSet);
this.beforePrototypeCreation(beanName);
//createBean
prototypeInstance = this.createBean(beanName, mbd, args);
} finally {
// this.prototypesCurrentlyInCreation.remove(beanNameSet);
this.afterPrototypeCreation(beanName);
}

beanInstance = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} else {
// 其他的scope -- request、session、global session, 的Ban的创建过程
String scopeName = mbd.getScope();

Scope scope = (Scope)this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}

try {
Object scopedInstance = scope.get(beanName, () -> {
this.beforePrototypeCreation(beanName);

Object var4;
try {
// 创建Bean
var4 = this.createBean(beanName, mbd, args);
} finally {
this.afterPrototypeCreation(beanName);
}

return var4;
});
beanInstance = this.getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
}
} finally {
beanCreation.end();
}
}
return this.adaptBeanInstance(name, beanInstance, requiredType);
}

AbstractAutowireCapableBeanFactory

createBean()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
RootBeanDefinition mbdToUse = mbd;
// 加载Bean的class
Class<?> resolvedClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
try {
// 准备方法覆盖
mbdToUse.prepareMethodOverrides();
}
Object beanInstance;
try {
// 实例化之前 InstantiationAwareBeanPostProcessor ## postProcessBeforeInstantiation()
beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);
if (beanInstance != null) {
return beanInstance;
}
}
try {
// 实例化 以及之后的操作
beanInstance = this.doCreateBean(beanName, mbdToUse, args);
return beanInstance;
}
}

doCreateBean()

实例化以及之后操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
}

if (instanceWrapper == null) {
// 创建实例 Wrapper实例 -- 会初始化 BeanWrapper的方法 ConversionService(转换)
instanceWrapper = this.createBeanInstance(beanName, mbd, args);
}
// wrapperd的包装属性
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
synchronized(mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// MergedBeanDefinitionPostProcessors接口的方法调用
this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
mbd.postProcessed = true;
}
}
// 判断是否由循环依赖导致的 earlySingleton
boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
if (earlySingletonExposure) {
// 添加三级缓存的 ObjectFactory 用于aop生成代理对象
this.addSingletonFactory(beanName, () -> {
return this.getEarlyBeanReference(beanName, mbd, bean);
});
}
Object exposedObject = bean;
try {
// 实例化之后 填充属性
this.populateBean(beanName, mbd, instanceWrapper);
// 初始化
exposedObject = this.initializeBean(beanName, exposedObject, mbd);
}
if (earlySingletonExposure) {
Object earlySingletonReference = this.getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
} else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
String[] dependentBeans = this.getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
String[] var12 = dependentBeans;
int var13 = dependentBeans.length;

for(int var14 = 0; var14 < var13; ++var14) {
String dependentBean = var12[var14];
if (!this.removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
}
try {
this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
return exposedObject;
}
}

doCreateBean() ## populateBean()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
} else {
if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
Iterator var4 = this.getBeanPostProcessors().iterator();
while(var4.hasNext()) {
BeanPostProcessor bp = (BeanPostProcessor)var4.next();
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
// InstantiationAwareBeanPostProcessor ## postProcessAfterInstantiation()
// 实例化之后的postProcess
// 自动注入AutowiredAnnotationBeanPostProcessor ## postProcessProperties()
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}

PropertyValues pvs = mbd.hasPropertyValues() ? mbd.getPropertyValues() : null;
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
// 自动注入
if (resolvedAutowireMode == 1 || resolvedAutowireMode == 2) {
MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs);
if (resolvedAutowireMode == 1) {
// byname
this.autowireByName(beanName, mbd, bw, newPvs);
}

if (resolvedAutowireMode == 2) {
// bytype
this.autowireByType(beanName, mbd, bw, newPvs);
}

pvs = newPvs;
}

boolean hasInstAwareBpps = this.hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = mbd.getDependencyCheck() != 0;
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}

Iterator var9 = this.getBeanPostProcessors().iterator();

while(var9.hasNext()) {
BeanPostProcessor bp = (BeanPostProcessor)var9.next();
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
// 参数填充
// InstantiationAwareBeanPostProcessor ## postProcessProperties()
PropertyValues pvsToUse = ibp.postProcessProperties((PropertyValues)pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// InstantiationAwareBeanPostProcessor ## InstantiationAwareBeanPostProcessor()
pvsToUse = ibp.InstantiationAwareBeanPostProcessor((PropertyValues)pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}

pvs = pvsToUse;
}
}
}

if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
//
this.checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs);
}

if (pvs != null) {
// 如果需要注入的属性不为空
// 通过set方法注入的入口 (注入非注解方式注入的属性)
// https://www.cnblogs.com/fnlingnzb-learner/p/10694592.html
this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs);
}

}
}

// 注入setter
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (!pvs.isEmpty()) {
if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl)bw).setSecurityContext(this.getAccessControlContext());
}

MutablePropertyValues mpvs = null;
List original;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues)pvs;
if (mpvs.isConverted()) {
try {
bw.setPropertyValues(mpvs);
return;
} catch (BeansException var18) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Error setting property values", var18);
}
}
//
original = mpvs.getPropertyValueList();
} else {
original = Arrays.asList(pvs.getPropertyValues());
}
// 属性转化
TypeConverter converter = this.getCustomTypeConverter();
if (converter == null) {
converter = bw;
}

BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, (TypeConverter)converter);
List<PropertyValue> deepCopy = new ArrayList(original.size());
boolean resolveNecessary = false;
Iterator var11 = original.iterator();

while(true) {
while(var11.hasNext()) {
PropertyValue pv = (PropertyValue)var11.next();
if (pv.isConverted()) {
deepCopy.add(pv);
} else {
String propertyName = pv.getName();
Object originalValue = pv.getValue();
if (originalValue == AutowiredPropertyMarker.INSTANCE) {
Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
}
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
convertedValue = this.convertForProperty(resolvedValue, propertyName, bw, (TypeConverter)converter);
}

if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}

deepCopy.add(pv);
} else if (convertible && originalValue instanceof TypedStringValue && !((TypedStringValue)originalValue).isDynamic() && !(convertedValue instanceof Collection) && !ObjectUtils.isArray(convertedValue)) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
} else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}

if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}

try { // Setter注入
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
return;
}
}
}
}

doCreateBean() ## initializeBean()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
// Aware 回调 设置属性
// 1.((BeanNameAware)bean).setBeanName(beanName);
// 2. ((BeanClassLoaderAware)bean).setBeanClassLoader(bcl);
// 3.((BeanFactoryAware)bean).setBeanFactory(this);
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(() -> {
// 设置Aware属性
this.invokeAwareMethods(beanName, bean);
return null;
}, this.getAccessControlContext());
} else {
// 设置Aware属性
this.invokeAwareMethods(beanName, bean);
}
// 初始化之前的方法
// BeanPostProcessor ## postProcessBeforeInitialization()
Object wrappedBean = bean;()
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
}

try {
// 执行初始化方法
// ((InitializingBean)bean).afterPropertiesSet();
this.invokeInitMethods(beanName, wrappedBean, mbd);
}
// 初始化之后的方法
// BeanPostProcessor ## postProcessAfterInitialization()
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}

return wrappedBean;
}

// 第二种调用
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
Object beanInstance;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged(() -> {
return this.getInstantiationStrategy().instantiate(mbd, beanName, this);
}, this.getAccessControlContext());
} else {
beanInstance = this.getInstantiationStrategy().instantiate(mbd, beanName, this);
}
// 封装BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
this.initBeanWrapper(bw);
return bw;
}
}

initializeBean() ## invokeInitMethods()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable {
boolean isInitializingBean = bean instanceof InitializingBean;
// afterPropertiesSet
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
// InitializingBean ## afterPropertiesSet()
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(() -> {
// 调用InitializingBean ## afterPropertiesSet()方法
((InitializingBean)bean).afterPropertiesSet();
return null;
}, this.getAccessControlContext());
} catch (PrivilegedActionException var6) {
throw var6.getException();
}
} else {
((InitializingBean)bean).afterPropertiesSet();
}
}

if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) && (!isInitializingBean || !"afterPropertiesSet".equals(initMethodName)) && !mbd.isExternallyManagedInitMethod(initMethodName)) {
this.invokeCustomInitMethod(beanName, bean, mbd);
}
}

}

AutowiredAnnotationBeanPostProcessor

1
2
3
4
5
6
7
8
9
10
11
12
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
InjectionMetadata metadata = this.findAutowiringMetadata(beanName, bean.getClass(), pvs);

try {
metadata.inject(bean, beanName, pvs);
return pvs;
} catch (BeanCreationException var6) {
throw var6;
} catch (Throwable var7) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", var7);
}
}

image-20230403224847280

FacotryBean

Bean的初始化入口

AbstracApplicationContext ## refresh() ## finishBeanFactoryInitialization() ## beanFactory.preInstantiateSingletons();

DefaultListableBeanFactory ## preInstantiateSingletons() // 实例化Bean和FacotryBean的重点方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public void preInstantiateSingletons() throws BeansException {
do {
while(true) {
// 已经实例化的bean
Object singletonInstance = this.getSingleton(beanName);
// 如果没有, 创建bean

this.getBean(beanName);
}
} while(!(bean instanceof FactoryBean));

// FactoryBean
FactoryBean<?> factory = (FactoryBean)bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
SmartFactoryBean var10000 = (SmartFactoryBean)factory;
((SmartFactoryBean)factory).getClass();
isEagerInit = (Boolean)AccessController.doPrivileged(var10000::isEagerInit, this.getAccessControlContext());
} else {
isEagerInit = factory instanceof SmartFactoryBean && ((SmartFactoryBean)factory).isEagerInit();
}

if (isEagerInit) {
this.getBean(beanName);
}
}

DefaultSingletonBeanRegistry ### getSingleton(beanName) // 该方法用于获取已经 实例化的 Bean

DefaultSingletonBeanRegistry

1
2
3
4
5
6
7
8
9
10
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
// 三级缓存解决循环依赖问题
private final Map<String, Object> singletonObjects = new ConcurrentHashMap(256);
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap(16);
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap(16);
// 正在创建的Bean名字集合
private final Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap(16));
private final Set<String> inCreationCheckExclusions = Collections.newSetFromMap(new ConcurrentHashMap(16));

}

image-20230403233526671

获取单例对象,并且解决循环依赖问题

循环依赖问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
// 判断是否正在 初始化参数
if (singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized(this.singletonObjects) {
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// 从 正在实例化中的Map取出 实例
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
// ObjectFactory函数式方法调用
// ## 1.创建实例对象 2. AOP代理对象的创建 / 3.实例对象获取
ObjectFactory<?> singletonFactory = (ObjectFactory)this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}

return singletonObject;
}

ObjectFactory

三个作用:1.创建实例对象

​ 2. AOP代理对象的创建 3.实例对象获取

1
2
3
4
@FunctionalInterface
public interface ObjectFactory<T> {
T getObject() throws BeansException;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// doGetBean() ## 	
// 实例化之前
// 1.创建实例对象
sharedInstance = this.getSingleton(beanName, () -> {
try {
// 如果SingletonObjects没有,调用方法创建Bean
return this.createBean(beanName, mbd, args);
} catch (BeansException var5) {
this.destroySingleton(beanName);
throw var5;
}
});
// doCreateBean() ##
// 实例化之后
// 2. AOP代理对象的创建 3.实例对象获取
this.addSingletonFactory(beanName, () -> {
// 如果没有,则进入getEarlyBeanReference()
// SmartInstantiationAwareBeanPostProcessor ## getEarlyBeanReference()
// 如果需要Aop动态代理,则调用AbstractAutoProxyCreator ## wrapIfNecessary()返回 Porxy代理对象
// 否则, 直接返回bean
return this.getEarlyBeanReference(beanName, mbd, bean);
});

已经实例化的beanname

image-20230404145015644

依赖注入

寻找注入点

@Autowired注入点的寻找有两个地方 : AnnotatedBeanDefinitionReader 的注册BeanDefinition时寻找;AutowiredAnnotationBeanPostProcessor的 findAutowiredAnnotation()方法进行寻找

生成 MergedAnnotations

入口一

1
2
3
4
5
AnnotatedBeanDefinitionReader ## doRegisterBean()
-> AnnotatedGenericBeanDefinition ## AnnotatedGenericBeanDefinition()
-> AnnotationMetadata ## introspect()
-> StandardAnnotationMetadata ## from()
-> TypeMappedAnnotations ## from()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// AnnotatedBeanDefinitionReader 
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name, @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier, @Nullable BeanDefinitionCustomizer[] customizers) {
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
}

// AnnotatedGenericBeanDefinition
public AnnotatedGenericBeanDefinition(Class<?> beanClass) {
this.setBeanClass(beanClass);
this.metadata = AnnotationMetadata.introspect(beanClass);
}

//AnnotationMetadata
static AnnotationMetadata introspect(Class<?> type) {
return StandardAnnotationMetadata.from(type);
}

// StandardAnnotationMetadata
public StandardAnnotationMetadata(Class<?> introspectedClass, boolean nestedAnnotationsAsMap) {
super(introspectedClass);
this.mergedAnnotations = MergedAnnotations.from(introspectedClass, SearchStrategy.INHERITED_ANNOTATIONS, RepeatableContainers.none());
this.nestedAnnotationsAsMap = nestedAnnotationsAsMap;
}

// MergedAnnotations
static MergedAnnotations from(AnnotatedElement element) {
return from(element, MergedAnnotations.SearchStrategy.DIRECT);
}
static MergedAnnotations from(AnnotatedElement element, MergedAnnotations.SearchStrategy searchStrategy) {
return from(element, searchStrategy, RepeatableContainers.standardRepeatables());
}
static MergedAnnotations from(AnnotatedElement element, MergedAnnotations.SearchStrategy searchStrategy, RepeatableContainers repeatableContainers) {
return from(element, searchStrategy, repeatableContainers, AnnotationFilter.PLAIN);
}
static MergedAnnotations from(AnnotatedElement element, MergedAnnotations.SearchStrategy searchStrategy, RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
Assert.notNull(repeatableContainers, "RepeatableContainers must not be null");
Assert.notNull(annotationFilter, "AnnotationFilter must not be null");
// 下一个入口
return TypeMappedAnnotations.from(element, searchStrategy, repeatableContainers, annotationFilter);
}

// TypeMappedAnnotations ## from()
static MergedAnnotations from(AnnotatedElement element, SearchStrategy searchStrategy, RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
return (MergedAnnotations)(AnnotationsScanner.isKnownEmpty(element, searchStrategy) ? NONE : new TypeMappedAnnotations(element, searchStrategy, repeatableContainers, annotationFilter));
}
// AnnotationsScanner ##

// TypeMappedAnnotations ## 构造器
private TypeMappedAnnotations(AnnotatedElement element, SearchStrategy searchStrategy, RepeatableContainers repeatableContainers, AnnotationFilter annotationFilter) {
this.source = element;
this.element = element;
this.searchStrategy = searchStrategy;
this.annotations = null;
this.repeatableContainers = repeatableContainers;
this.annotationFilter = annotationFilter;
}

image-20230422095010110

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public interface MergedAnnotations extends Iterable<MergedAnnotation<Annotation>> {
public static enum SearchStrategy {
DIRECT,
INHERITED_ANNOTATIONS,
SUPERCLASS,
TYPE_HIERARCHY,
TYPE_HIERARCHY_AND_ENCLOSING_CLASSES;

private SearchStrategy() {
}
}
}

final class TypeMappedAnnotations implements MergedAnnotations {
static final MergedAnnotations NONE;
@Nullable
private final Object source;
@Nullable
private final AnnotatedElement element;
@Nullable
private final SearchStrategy searchStrategy;
@Nullable
private final Annotation[] annotations;
private final RepeatableContainers repeatableContainers;
private final AnnotationFilter annotationFilter;
@Nullable
private volatile List<TypeMappedAnnotations.Aggregate> aggregates;
}

image-20230422095029546

1
2
3
public interface MergedAnnotation<A extends Annotation> {
String VALUE = "value";
}

image-20230422100239271

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
abstract class AnnotationsScanner {
private static final Annotation[] NO_ANNOTATIONS = new Annotation[0];
private static final Method[] NO_METHODS = new Method[0];
private static final Map<AnnotatedElement, Annotation[]> declaredAnnotationCache = new ConcurrentReferenceHashMap(256);
private static final Map<Class<?>, Method[]> baseTypeMethodsCache = new ConcurrentReferenceHashMap(256);

// SearchStrategy searchStrategy
private static <C, R> R processClass(C context, Class<?> source, SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
switch(searchStrategy) {
case DIRECT:
return processElement(context, source, processor);
case INHERITED_ANNOTATIONS:
return processClassInheritedAnnotations(context, source, searchStrategy, processor);
case SUPERCLASS:
return processClassHierarchy(context, source, processor, false, false);
case TYPE_HIERARCHY:
return processClassHierarchy(context, source, processor, true, false);
case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
return processClassHierarchy(context, source, processor, true, true);
default:
throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
}
}

static boolean isKnownEmpty(AnnotatedElement source, SearchStrategy searchStrategy) {
if (hasPlainJavaAnnotationsOnly((Object)source)) {
return true;
} else if (searchStrategy != SearchStrategy.DIRECT && !isWithoutHierarchy(source, searchStrategy)) {
return false;
} else if (source instanceof Method && ((Method)source).isBridge()) {
return false;
} else {
return getDeclaredAnnotations(source, false).length == 0;
}
}
}

image-20230422100745459

入口二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// AutowiredAnnotationBeanPostProcessor ## postProcessProperties()
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
InjectionMetadata metadata = this.findAutowiringMetadata(beanName, bean.getClass(), pvs);
}
// findAutowiringMetadata()
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
String cacheKey = StringUtils.hasLength(beanName) ? beanName : clazz.getName();
InjectionMetadata metadata = (InjectionMetadata)this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized(this.injectionMetadataCache) {
metadata = (InjectionMetadata)this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
// 构建AutowriedMetadate
metadata = this.buildAutowiringMetadata(clazz);
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}

return metadata;
}
// buildAutowiringMetadata()
private InjectionMetadata buildAutowiringMetadata(Class<?> clazz) {
ReflectionUtils.doWithLocalFields(targetClass, (field) -> {
MergedAnnotation<?> ann = this.findAutowiredAnnotation(field);
}
}
// findAutowiredAnnotation()
private MergedAnnotation<?> findAutowiredAnnotation(AccessibleObject ao) {
// 同入口一的 MergedAnnotations的from方法
MergedAnnotations annotations = MergedAnnotations.from(ao);
}
//MergedAnnotations ## from()

(13条消息) Spring @Value注解解析源码_@value源码_CRUD的W的博客-CSDN博客

AutowiredAnnotationBeanPostProcessor

依赖注入@Autowired, @Value,@Inject

@Value — 需要PropertySourcesPlaceholderConfigurer (自动注入) 解析 ${},获取PropertySource的application的属性值,进行注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
protected final Log logger = LogFactory.getLog(this.getClass());
private final Set<Class<? extends Annotation>> autowiredAnnotationTypes = new LinkedHashSet(4);
private String requiredParameterName = "required";
private boolean requiredParameterValue = true;
private int order = 2147483645;
@Nullable
private ConfigurableListableBeanFactory beanFactory;
private final Set<String> lookupMethodsChecked = Collections.newSetFromMap(new ConcurrentHashMap(256));
private final Map<Class<?>, Constructor<?>[]> candidateConstructorsCache = new ConcurrentHashMap(256);
private final Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap(256);
// 添加可以自动注入的 annotationtype -- Autowired,Value,Inject
public AutowiredAnnotationBeanPostProcessor() {
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
try {
this.autowiredAnnotationTypes.add(ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
this.logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
} catch (ClassNotFoundException var2) {
}

}


// 内部类 InjectedElement : 两个子类
// AutowiredFieldElement(自动注入属性) AutowiredMethodElement(自动注入方法)
public abstract static class InjectedElement {
// java.lang.reflect == a single member (a field or a method) or a constructor.
// 一个属性、一个方法或者一个构造方法
protected final Member member;
protected final boolean isField;

protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs) throws Throwable {
if (this.isField) {
Field field = (Field)this.member;
ReflectionUtils.makeAccessible(field);
// 属性注入
field.set(target, this.getResourceToInject(target, requestingBeanName));
} else {
if (this.checkPropertySkipping(pvs)) {
return;
}
try { // 方法 执行注入
Method method = (Method)this.member;
ReflectionUtils.makeAccessible(method);
method.invoke(target, this.getResourceToInject(target, requestingBeanName));
} catch (InvocationTargetException var5) {
throw var5.getTargetException();
}
}

}
}
//
private class AutowiredMethodElement extends InjectedElement {
private final boolean required;
private volatile boolean cached;
@Nullable
private volatile Object[] cachedMethodArguments;
///
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
if (!this.checkPropertySkipping(pvs)) {
Method method = (Method)this.member;
Object[] arguments;
if (this.cached) {
try {
arguments = this.resolveCachedArguments(beanName);
} catch (NoSuchBeanDefinitionException var8) {
arguments = this.resolveMethodArguments(method, bean, beanName);
}
} else {
arguments = this.resolveMethodArguments(method, bean, beanName);
}

if (arguments != null) {
try {
// 设置反射权限 method.setAccessible(true);
ReflectionUtils.makeAccessible(method);
method.invoke(bean, arguments);
} catch (InvocationTargetException var7) {
throw var7.getTargetException();
}
}
}
}
}
// 自动注入属性 ----@Autowired, @Value, @Inject
private class AutowiredFieldElement extends InjectedElement {
// 是否必须
private final boolean required;
private volatile boolean cached;
@Nullable // 缓存值
private volatile Object cachedFieldValue;
// 属性的自动注入
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Field field = (Field)this.member;
Object value; // 获取需要注入的属性的值
if (this.cached) {
try {
value = AutowiredAnnotationBeanPostProcessor.this.resolvedCachedArgument(beanName, this.cachedFieldValue);
} catch (NoSuchBeanDefinitionException var7) {
value = this.resolveFieldValue(field, bean, beanName);
}
} else {
value = this.resolveFieldValue(field, bean, beanName);
}

if (value != null) {
// 权限啊设置
ReflectionUtils.makeAccessible(field);
// 属性设置
field.set(bean, value);
}

}
}

}

image-20230416201130823

DependencyDescriptor

保存注入点的信息 —

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package org.springframework.beans.factory.config;

@SuppressWarnings("serial")
public class DependencyDescriptor extends InjectionPoint implements Serializable {

// 保存所包装依赖(成员属性或者成员方法的某个参数)所在的声明类,
// 其实该信息在 field/methodParameter 中已经隐含
private final Class<?> declaringClass;

// 如果所包装依赖是成员方法的某个参数,则这里记录该成员方法的名称
@Nullable
private String methodName;

// 如果所包装的是成员方法的某个参数,则这里记录该参数的类型
@Nullable
private Class<?>[] parameterTypes;

// 如果所包装的是成员方法的某个参数,则这里记录该参数在该函数参数列表中的索引
private int parameterIndex;

//如果所包装的是成员属性,则这里记录该成员属性的名称
@Nullable
private String fieldName;

// 标识所包装依赖是否必要依赖
private final boolean required;

// 标识所包装依赖是否需要饥饿加载
private final boolean eager;

// 标识所包装依赖的嵌套级别
private int nestingLevel = 1;

// 标识所包装依赖的包含者类,通常和声明类是同一个
@Nullable
private Class<?> containingClass;

// 所包装依赖 ResolvableType 的缓存
@Nullable
private transient volatile ResolvableType resolvableType;

// 所包装依赖 TypeDescriptor 的缓存
@Nullable
private transient volatile TypeDescriptor typeDescriptor;
}

spring,spring boot注入属性的所有方式

在Spring和Spring Boot中,有多种方式可以注入属性。以下是常用的几种方式:

  1. 使用@Value注解:@Value注解可以在类成员变量上使用,用于将属性值注入到该变量中。这个值可以从application.properties或application.yml配置文件中读取,也可以通过SpEL表达式来计算。

    ​ – AutowiredAnnotatedBeanPostProcessor

  2. 使用@ConfigurationProperties注解:@ConfigurationProperties注解可以在@Configuration类或@Component类上使用,用于将一个或多个属性值注入到对象中。该注解可以自定义前缀,以匹配多个属性。

  3. 使用@PropertySource:@PropertySource注解可以引入其他的属性文件,从而扩展属性的来源。同时还需要结合@Value或@ConfigurationProperties注解使用,以将属性值注入到程序中。

  4. 使用Environment:Environment接口可用于获取应用程序的属性(例如,System属性、环境变量、命令行参数等)并使用这些属性进行配置。

  5. 使用Spring Expression Language(SpEL):SpEL是一种用于访问对象图表达式语言,可用于计算@Value注解中的属性值或@ConfigurationProperties注解中的默认值。

  6. 使用@Autowired注解:@Autowired注解可用于将属性注入到bean中。当属性处于单例范围内时,它们将在容器启动时被自动装配。 – AutowiredAnnotatedBeanPostProcessor

这些是最常用的一些方式,但不限于这些。在复杂的情况下,可以结合使用这些注入方式来实现属性的注入。

除了上述提到的几种常用的属性注入方式,还有以下注入方式:

  1. 使用@Resource注解:@Resource注解与@Autowired注解类似,在将属性注入到bean中时使用。它可以指定属性名称或类型,并且支持JSR-250标准。 – CommonBeanPostProcessor
  2. 使用@Inject注解:@Inject注解是Java依赖注入规范(JSR-330)中定义的,与@Autowired注解类似。通过使用@Inject注解,可以将依赖项注入到应用程序中。 – AutowiredAnnotatedBeanPostProcessor
  3. 使用构造函数注入:构造函数注入是另一种将属性值注入到bean中的方式。使用构造函数注入可以使代码更加清晰和易于测试,因为所有必需的依赖项都可以在构造函数中声明。
  4. 使用工厂方法注入:工厂方法注入类似构造函数注入,但是允许属性值被注入到一个静态工厂方法中并返回具有这些属性的实例。
  5. 使用@Bean注解:@Bean注解可以用于将属性注入到Spring的IoC容器中。此外,@Bean注解还可以用于创建一个新的bean,作为其他bean的依赖项注入。 — ConfigurationClasPostProcessor
  6. 使用Setter方法注入:Setter方法注入是另一种常用的方式,其基本思想是在setter方法上使用@Autowired注解来注入属性。 — populateBean() ## applyPropertyValues()

需要注意的是,不同的注入方式适用于不同的场景和需求,开发人员在使用时需要根据具体情况进行选择

aop,aware, BeanPostProcessor,

BeanPostProcessor

1
2
3
4
5
6
7
8
9
10
11
public interface BeanPostProcessor {
// 初始化之前
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}

// 初始化之后
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}

BeanPostProcessorCache

1
2
3
4
5
6
7
8
9
static class BeanPostProcessorCache {
final List<InstantiationAwareBeanPostProcessor> instantiationAware = new ArrayList();
final List<SmartInstantiationAwareBeanPostProcessor> smartInstantiationAware = new ArrayList();
final List<DestructionAwareBeanPostProcessor> destructionAware = new ArrayList();
final List<MergedBeanDefinitionPostProcessor> mergedDefinition = new ArrayList();

BeanPostProcessorCache() {
}
}
InstantiationAwareBeanPostProcessor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
// 实例化之前
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
// 实例化之后
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}

// 属性设置 PropertyValues ---设置属性后,对pvs进行增强
// AutowiredAnnotationBeanPostProcessor 实现自动注入功能
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
return null;
}
}
SmartInstantiationAwareBeanPostProcessor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
// 推断Bean的类型
default Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException {
return null;
}

// 推断 候选的构造函数
default Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
// 获取实例化后,初始化前的对象实例
// 用于获取AopProxy对象,实现Aop增强和循环依赖的解决
default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
return bean;
}
}
MergedBeanDefinitionPostProcessor
1
2
3
4
5
6
7
public interface MergedBeanDefinitionPostProcessor extends BeanPostProcessor {
// 合并BeanDefinition
void postProcessMergedBeanDefinition(RootBeanDefinition var1, Class<?> var2, String var3);
// 重设BeanDefnition
default void resetBeanDefinition(String beanName) {
}
}

InitializingBean

1
2
3
4
5
6
public interface InitializingBean {
// invokeInitMethods()方法调用
// 在populateBean()属性填充之后调用
// invokeCustomInitMethod() 初始化方法执行之前
void afterPropertiesSet() throws Exception;
}

AutowireCapableBeanFactory - 注入方式

1
2
3
4
5
6
public interface AutowireCapableBeanFactory extends BeanFactory {
int AUTOWIRE_NO = 0;
int AUTOWIRE_BY_NAME = 1;
int AUTOWIRE_BY_TYPE = 2;
int AUTOWIRE_CONSTRUCTOR = 3;
}

image-20230404141739106

AbstractAutowireCapableBeanFactory

image-20230404141636814

AOP 模块

Aop和AspectJ原理

AOP面向切面编程是一种编程思想

AspectJ也实现了AOP的功能,且其实现方式更为简捷,使用更为方便,而且还支持注解式开发。所以,Spring又将AspectJ对于AOP的实现也引入到了自己的框架中。

  • Aspect,切面在实际的应用中,切面通常是指封装的用于横向插入系统功能,比如事务日志的类,该类被spring容器识别为切面,需要在配置文件中通过<bean>来指定。
  • Joinpiont,连接点,在程序执行过程中的某个阶段点。它实际上是对象的一个操作,例如方法的调用或异常的抛出。在spring AOP中连接点就是指方法的调用。
  • Pointcut,切入点,切入点是指切面与程序流程的交叉点,即那些需要处理的连接点,通常在程序中切入点是指。类或者是方法名,比如说某个通知要应用到所有的以add开头的方法中。那么所有满足这一规则的方法都是切入点。
  • Adivce,通知增强处理,AOP 框架在特定的切入点执行增强处理,即在定义好的切入点处理所需要执行的程序代码,你可以理解其为切面类中的方法,它是切面的具体实现。
  • Target Object ,目标对象,是指所有通知的对象。也称为北增强对象。如果AOP框架采用的是动态的AOP实现,那么该对象就是一个被代理对象。
  • Proxy ,代理,将通知应用到目标对象之后被动态创建的对象。
  • Weaving, 织入,将切面代码插入目标对象上,从而生成代理对象的过程。

Aop框架和springframework.aop

image-20230405164119306

重点类:

AopProxy

spring将JDK动态代理和 Cglib动态代理全部封装为 AopProxy,用于aop时,进行增强操作

image-20230405165929687

1
2
3
4
5
6
// CglibAopProxy 和 JDKDynamicAopProxy 实现通过两种方式获取代理对象
public interface AopProxy {
Object getProxy();

Object getProxy(@Nullable ClassLoader var1);
}

CglibAopProxy

CallBack,MethodInterceptor接口

1
2
3
class CglibAopProxy implements AopProxy, Serializable {
// 定义了许多的 MethodInterceptor实现类,每个实现类不同的增强方式。
}

image-20230405180654563

CallBack

CGLIB回调接口,通过实现该接口,用于处理回调事件

JdkDynamicAopProxy

效果和JDK动态代理差不多,为Spring自己封装的动态代理逻辑

1
2
3
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {

}
1
2
3
4
5
package org.springframework.cglib.proxy;
// 等同package java.lang.reflect;
public interface InvocationHandler extends Callback {
Object invoke(Object var1, Method var2, Object[] var3) throws Throwable;
}

image-20230405165729107

JDK动态代理

流程:

1.定义一个接口SellTickets,并有一个方法sell() – (假设);

2.被代理类实现接口方法

3.被代理类调用Proxy的static方法 newProxyInstance() 创建代理对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Object $Proxy0 = Proxy.newProxyInstance(station.getClass().getClassLoader(),
station.getClass().getInterfaces(),
new InvocationHandler() {
/*
InvocationHandler中invoke方法参数说明:
proxy : 代理对象
method : 对应于在代理对象上调用的接口方法的 Method 实例
args : 代理对象调用接口方法时传递的实际参数
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理点收取一些服务费用(JDK动态代理方式)");
//执行真实对象
Object result = method.invoke(station, args);
return result;
}
});

4.类加载时自动生成$Proxy0对象,继承Proxy对象实现SellTickets的sell()方法

1
2
3
4
5
6
public final class $Proxy0 extends Proxy implements SellTickets {
// 自动生成的接口的代理方法
public final void sell() {
this.h.invoke(this, m3, null);
}
}

5.方法调用了传入的InvocationHandler 函数式接口 (增强方法)

Proxy

1
2
3
4
5
6
7
8
9
// 获取代理对象
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
// 重点,用它调用 代理类的方法执行
InvocationHandler h);
// 自动生成的接口的代理方法
public final void sell() {
this.h.invoke(this, m3, null);
}

InvacationHandler

1
2
3
4
5
6
7
8
// 用户编写的增强方法
public interface InvocationHandler {
// proxy : 代理对象
// method : 对应于在代理对象上调用的接口方法的 Method 实例
// args : 代理对象调用接口方法时传递的实际参数
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}

CGLIB动态代理

(1条消息) spring中cglib动态代理_springcglib动态代理_唂雨云的博客-CSDN博客

源码详解系列(一)–cglib动态代理的使用和分析 - 知乎 (zhihu.com)

原理:

备注:可以增强被代理对象的所有方法,但是只能在intercept()方法中定义方法调用 前后增强逻辑;

Enhancer
MethodInterceptor
1
2
3
public interface MethodInterceptor extends Callback {
Object intercept(Object var1, Method var2, Object[] var3, MethodProxy var4) throws Throwable;
}
MethodProxy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class MethodProxy {
private static class FastClassInfo {
FastClass f1;
FastClass f2;
int i1;
int i2;

private FastClassInfo() {
}
}
private void init() {
if (this.fastClassInfo == null) {
synchronized(this.initLock) {
if (this.fastClassInfo == null) {
MethodProxy.CreateInfo ci = this.createInfo;
MethodProxy.FastClassInfo fci = new MethodProxy.FastClassInfo();
fci.f1 = helper(ci, ci.c1);
fci.f2 = helper(ci, ci.c2);
fci.i1 = fci.f1.getIndex(this.sig1);
fci.i2 = fci.f2.getIndex(this.sig2);
this.fastClassInfo = fci;
this.createInfo = null;
}
}
}


public Object invoke(Object obj, Object[] args) throws Throwable {
try {
this.init();
MethodProxy.FastClassInfo fci = this.fastClassInfo;
return fci.f1.invoke(fci.i1, obj, args);
}
}
FastClass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public abstract class FastClass {
private Class type;
public Object invoke(String name, Class[] parameterTypes, Object obj, Object[] args) throws InvocationTargetException {
// 所有的方法都是abstract方法,在生成具体的FastClass会创建具体的 代理类
// 代理类包含具体实现
return this.invoke(this.getIndex(name, parameterTypes), obj, args);
}
/*
//传入参数:
//n:方法索引
//o:代理类实例
//array:方法输入参数
public Object invoke(final int n, final Object o, final Object[] array) throws InvocationTargetException {
final UserController$$EnhancerByCGLIB$$e6f193aa userController$$EnhancerByCGLIB$$e6f193aa = (UserController$$EnhancerByCGLIB$$e6f193aa)o;
try {
switch (n) {
case 0: {
return new Boolean(userController$$EnhancerByCGLIB$$e6f193aa.equals(array[0]));
}
case 1: {
return userController$$EnhancerByCGLIB$$e6f193aa.toString();
}
case 2: {
return new Integer(userController$$EnhancerByCGLIB$$e6f193aa.hashCode());
}
case 3: {
return userController$$EnhancerByCGLIB$$e6f193aa.clone();
}
// ·······
case 24: {
// 通过匹配方法索引,直接调用该方法,这个方法里将直接调用目标类的方法
userController$$EnhancerByCGLIB$$e6f193aa.CGLIB$update$0();
return null;
}
// ·······

}
catch (Throwable t) {
throw new InvocationTargetException(t);
}
throw new IllegalArgumentException("Cannot find matching method/constructor");
}*/
}

备注:调用抽象方法,具体实现需要动态生成代理对象时,创建

image-20230405175501722

流程:

不需要单独实现接口,让被代理类实现,通过继承被代理类 覆盖需要加强的方法,进行方法的增强操作。

1.实现MethodInterceptor接口,实现intercept() 方法,即增强方法

2.创建需要被代理类的Enhancer (代理类) — 会生成被代理对象的子类

3.代理类调用被增强方法会自动 找到子类实现的覆盖方法,然后调用 intercepted()方法

4.在intercepted()方法 实现动态增强方法

备注:由于spring中很多时候无法通过继承同一个接口对象实现JDK动态代理,所以AOP的具体实现 主要是CGLIB动态代理。(@Transaction, @Aync等)

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class ProxyFactory implements MethodInterceptor {
// 需要被代理的对象
private Object target;

// 自定义方法,创建代理对象
public TrainStation getProxy() {
//创建Enhancer对象,类似于JDK动态代理的Proxy类,下一步就是设置几个参数
Enhancer enhancer =new Enhancer();
//设置父类的字节码对象
enhancer.setSuperclass(target.getClass());
//设置回调函数
enhancer.setCallback(this);
//创建代理对象
TrainStation obj = (TrainStation) enhancer.create();
return obj;
}

/**
* 通过 method 引用实例 Object result = method.invoke(target, args); 形式反射调用被代理类方法,
* target 实例代表被代理类对象引用, 初始化 CglibMethodInterceptor 时候被赋值 。但是Cglib不推荐使用这种方式
* @param obj 代表Cglib 生成的动态代理类 对象本身
* @param method 代理类中被拦截的接口方法 Method 实例
* @param args 接口方法参数
* @param methodProxy 用于调用父类真正的业务类方法。可以直接调用被代理类接口方法
* @return
* @throws Throwable
*/
// 这是增强方法
public TrainStation intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
// 有两种调用方式
System.out.println("代理点收取一些服务费用(CGLIB动态代理方式)");
// 一:通过反射调用 被代理类方法
// method.invoke(target, args);
// 二: 调用父类(被代理类)的方法
TrainStation result = (TrainStation) methodProxy.invokeSuper(obj, args);
return result;
}
}

暂定:

MethodValidationPostProcessor

方法执行前的校验 Validate

AbstractBeanFactoryAwareAdvisingPostProcessor继承自ProxyConfig

1
2
3
4
5
6
7
8
9
public class MethodValidationPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor implements InitializingBean {
private Class<? extends Annotation> validatedAnnotationType = Validated.class;
@Nullable
private Validator validator;
// Advice --
protected Advice createMethodValidationAdvice(@Nullable Validator validator) {
return validator != null ? new MethodValidationInterceptor(validator) : new MethodValidationInterceptor();
}
}

image-20230406200155882

MethodValidationInterceptor

image-20230405161939755

Aop和Aspect J的应用

在Spring AOP中,有几个关键的组件用于实现切面编程:

JointPoint(连接点):连接点是在应用程序执行过程中可以插入切面的点。连接点可以是类的属性、构造方法、原始方法或代理对象。在连接点上,切面可以执行额外的逻辑。

PointCut(切入点):切入点是用于定义在哪些连接点上应用切面的规则。切入点可以通过使用@Pointcut注解来定义,它可以匹配类或方法的名称、参数、注解等。切入点决定了切面在哪些连接点上生效。

Advice(增强方法):Advice是切面在特定连接点上执行的逻辑。它定义了在连接点上要执行的操作,例如在方法执行前后执行某些代码、抛出异常时执行某些代码等。Spring AOP提供了几种类型的Advice,包括前置通知(Before)、后置通知(After)、返回通知(AfterReturning)、异常通知(AfterThrowing)和环绕通知(Around)。

Advisor(顾问):Advisor是将切面和切入点组合在一起的对象。它包含了切面和切入点的信息,并决定了切面在哪些连接点上生效。

Advised(被增强对象):Advised是被增强的目标对象。它是应用切面的对象,切面会在Advised的连接点上执行增强方法。

包结构

image-20230405221715635

JoinPoint - 连接点

JointPoint(连接点):连接点是在应用程序执行过程中可以插入切面的点。连接点可以是类的属性、构造方法、原始方法或代理对象。在连接点上,切面可以执行额外的逻辑。

获取切入点的 方法 / 类 / 属性信息

1
2
3
4
5
6
7
8
public interface Joinpoint {
// 执行织入点的方法
Object proceed() throws Throwable;
// 获取 织入点的 方法的this指针
Object getThis();

AccessibleObject getStaticPart();
}

用户获取代理对象 – 即切入点-切入方法的动态代理对象Proxy,用于增强方法

Invocation
MethodInvocation
ConstructorInvocation
ProxyMethodInvocation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 获取类信息
public interface Joinpoint {
Object proceed() throws Throwable;

Object getThis();

AccessibleObject getStaticPart();
}
// 获取参数列表
public interface Invocation extends Joinpoint {
Object[] getArguments();
}
// 获取方法
public interface MethodInvocation extends Invocation {
Method getMethod();
}
// 获取构造函数
public interface ConstructorInvocation extends Invocation {
Constructor<?> getConstructor();
}
// 获取代理对象
public interface ProxyMethodInvocation extends MethodInvocation {
Object getProxy();
// 。。。。
}

image-20230405222028275

ProxyMethodInvocation -> ReflectivMethodInvocation -> CglibAopProxy( 内部类: CglibMethodInvocation ) 获取代理类

Advice – 通知

作用:通过实现 —用户方法执行的调用

Advice(增强方法):Advice是切面在特定连接点上执行的逻辑。它定义了在连接点上要执行的操作,例如在方法执行前后执行某些代码、抛出异常时执行某些代码等。Spring AOP提供了几种类型的Advice,包括前置通知(Before)、后置通知(After)、返回通知(AfterReturning)、异常通知(AfterThrowing)和环绕通知(Around)。

image-20230405222505694

BeforeAdvice , AfterAdvice

AspectJPrecedenceInformation

precedence :优先级

作用:实现Ordered接口,实现用于设置Advice执行的优先级,并能够获取当前方法的执行时机

1
2
3
4
5
6
7
8
9
public interface AspectJPrecedenceInformation extends Ordered {
String getAspectName();
///
int getDeclarationOrder();
//
boolean isBeforeAdvice();
//
boolean isAfterAdvice();
}

AbstractAspectJAdvice

调用的方法时增强方法,aspectJAdviceMethod

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public abstract class AbstractAspectJAdvice implements Advice, AspectJPrecedenceInformation, Serializable {
protected static final String JOIN_POINT_KEY = JoinPoint.class.getName();
private final Class<?> declaringClass;
private final String methodName;
private final Class<?>[] parameterTypes;
// 增强方法
protected transient Method aspectJAdviceMethod;
// 切入点
private final AspectJExpressionPointcut pointcut;
private final AspectInstanceFactory aspectInstanceFactory;
private String aspectName = "";
private int declarationOrder;
private String[] argumentNames;
private String throwingName;
@Nullable
private String returningName;
private Class<?> discoveredReturningType = Object.class;
private Class<?> discoveredThrowingType = Object.class;
private int joinPointArgumentIndex = -1;
private int joinPointStaticPartArgumentIndex = -1;
@Nullable
private Map<String, Integer> argumentBindings;
private boolean argumentsIntrospected = false;
@Nullable
private Type discoveredReturningGenericType;

// 反射 执行增强方法
protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable {
Object[] actualArgs = args;
if (this.aspectJAdviceMethod.getParameterCount() == 0) {
actualArgs = null;
}
try {
ReflectionUtils.makeAccessible(this.aspectJAdviceMethod);
return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);
}
}
}

image-20230405222931657

image-20230405222946836

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 主要参数
// JoinPoint JoinPointMatch Obejct(returnVal) Throwable

// before
public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
this.invokeAdviceMethod(this.getJoinPointMatch(), (Object)null, (Throwable)null);
}
// around -- 特殊:环绕通知需要在增强方法中, 通过JoinPoint.proceed() 调用被增强的方法
public Object invoke(MethodInvocation mi) throws Throwable {
if (!(mi instanceof ProxyMethodInvocation)) {
throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);
} else {
ProxyMethodInvocation pmi = (ProxyMethodInvocation)mi;
ProceedingJoinPoint pjp = this.lazyGetProceedingJoinPoint(pmi);
JoinPointMatch jpm = this.getJoinPointMatch(pmi);
return this.invokeAdviceMethod(pjp, jpm, (Object)null, (Throwable)null);
}
}
// after
public Object invoke(MethodInvocation mi) throws Throwable {
Object var2;
try {
var2 = mi.proceed();
} finally {
this.invokeAdviceMethod(this.getJoinPointMatch(), (Object)null, (Throwable)null);
}

return var2;
}

Interceptor

MethodInterceptor
1
2
3
4
@FunctionalInterface
public interface MethodInterceptor extends Interceptor {
Object invoke(MethodInvocation var1) throws Throwable;
}

AspectJAroudAdvice

增强方法:继承AbstractAspectJAdvice, MethodInterceptor, AspectJPrecedenceInformation

通过实现MethodInterceptor的invoke()方法,然后由CGLIB生成的动态代理对象,调用invoke()方法,实现方法的增强

1
2
3
4
5
6
public Object invoke(MethodInvocation mi) throws Throwable {
// XXXX
// 最终调用到AbstractAspectJAdvice的方法中
return this.invokeAdviceMethod(pjp, jpm, (Object)null, (Throwable)null);
// XXXXX
}
1
2
3
4
5
AspectJMethodBeforeAdvice 

AspectJAroudAdvice

AspectJAfterAdvice AspectJAfterReturnAdvice AspectJAfterThrowingAdvice

定义invoke()方法的调用顺序 增强方法调用和原方法调用

image-20230405222835592

Pointcut – 切入点

切点表达式

除了使用@Around("@annotation(authCheck)")来匹配带有特定注解的方法之外,Spring AOP还提供了其他几种方式来定义切面:

  1. 使用@Around("execution(* com.example.service.*.*(..))"):通过execution表达式匹配指定包下的所有方法,并在方法执行前后执行通知。
  2. 使用@Around("within(com.example.service.*)"):通过within表达式匹配指定包下的所有类的所有方法,并在方法执行前后执行通知。
  3. 使用@Around("bean(myService)"):通过bean表达式匹配指定名称的Bean的所有方法,并在方法执行前后执行通知。
  4. 使用@Around("args(java.lang.String)"):通过args表达式匹配指定参数类型的方法,并在方法执行前后执行通知。
  5. 使用@Around("target(com.example.service.MyService)"):通过target表达式匹配指定目标对象类型的方法,并在方法执行前后执行通知。
  6. 使用@Around("this(com.example.service.MyService)"):通过this表达式匹配实现指定接口的代理对象的方法,并在方法执行前后执行通知。

在Spring AOP中,切点(Pointcut)用于定义需要拦截的方法或类的集合。切点表达式(Pointcut Expression)是一种语法规则,用于描述切点的匹配规则。切点表达式可以与注解结合使用,以便更精确地选择要拦截的方法或类。

以下是一些常用的切点表达式和相关注解的说明:

  1. execution表达式:使用execution表达式可以匹配方法的执行。例如,execution(* com.example.service.*.*(..))表示匹配com.example.service包下的所有类的所有方法。
  2. within表达式:使用within表达式可以匹配指定包或类中的所有方法。例如,within(com.example.service.*)表示匹配com.example.service包下的所有类的所有方法。
  3. bean表达式:使用bean表达式可以匹配指定名称的Bean的所有方法。例如,bean(myService)表示匹配名称为myService的Bean的所有方法。
  4. args表达式:使用args表达式可以匹配指定参数类型的方法。例如,args(java.lang.String)表示匹配接受一个String类型参数的方法。
  5. target表达式:使用target表达式可以匹配指定目标对象类型的方法。例如,target(com.example.service.MyService)表示匹配实现com.example.service.MyService接口的目标对象的所有方法。
  6. this表达式:使用this表达式可以匹配实现指定接口的代理对象的方法。例如,this(com.example.service.MyService)表示匹配实现com.example.service.MyService接口的代理对象的所有方法。

这些切点表达式可以与注解结合使用,以进一步精确地选择要拦截的方法或类。例如,@Around("@annotation(authCheck)")表示匹配带有authCheck注解的方法,并在方法执行前后执行通知。

需要注意的是,切点表达式的语法和规则可以根据实际情况进行调整和扩展。可以根据具体的需求和场景选择合适的切点表达式和注解来定义切面。

希望这些信息对你有帮助。如果你有更多问题,请随时提问。

作用:

PointCut(切入点):切入点是用于定义在哪些连接点上应用切面的规则。切入点可以通过使用@Pointcut注解来定义,它可以匹配类或方法的名称、参数、注解等。切入点决定了切面在哪些连接点上生效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public interface Pointcut {
Pointcut TRUE = TruePointcut.INSTANCE;
// 获取类过滤
ClassFilter getClassFilter();
// 获取方法匹配器
MethodMatcher getMethodMatcher();
}
@Pointcut("execution(* concert.Performance.perform(int)) && args(num)") // 定义命名的切点
public void performance(int num) {

}
// 切入方法
public interface Performance {
public void perform(int num);
}

image-20230405231025354

ClassFilter

1
2
3
4
5
[ublic interface ClassFilter {
ClassFilter TRUE = TrueClassFilter.INSTANCE;
//
boolean matches(Class<?> var1);
}

image-20230405231238795

MethodMatcher

1
2
3
4
5
6
7
8
9
public interface MethodMatcher {
MethodMatcher TRUE = TrueMethodMatcher.INSTANCE;
//
boolean matches(Method var1, Class<?> var2);

boolean isRuntime();
//
boolean matches(Method var1, Class<?> var2, Object... var3);
}

image-20230405231331607

DynamicMethodMatcherPoincut

image-20230406104600568

AspectJExpressionPointcut

用于解析pointcut的表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
public class AspectJExpressionPointcut extends AbstractExpressionPointcut implements ClassFilter, IntroductionAwareMethodMatcher, BeanFactoryAware {
private static final Set<PointcutPrimitive> SUPPORTED_PRIMITIVES = new HashSet();
@Nullable
private Class<?> pointcutDeclarationScope;
private String[] pointcutParameterNames = new String[0];
private Class<?>[] pointcutParameterTypes = new Class[0];
// 通过 BeanFactoryAware ## setBeanFactory()设置属性
private BeanFactory beanFactory;
@Nullable
private transient ClassLoader pointcutClassLoader;
// pointcut的表达式
private transient PointcutExpression pointcutExpression;
private transient Map<Method, ShadowMatch> shadowMatchCache = new ConcurrentHashMap(32);

MethodMatcher :方法匹配

ClassFilter : 类匹配

Pointcut -> ExpressionPointcut : 获取切入点的表达式

BeanFactoryAware: 用于获取BeanFactory参数

image-20230405233548524

Advisor – 通知者

作用:Advisor(顾问):Advisor是将切面和切入点组合在一起的对象。它包含了切面和切入点的信息,并决定了切面在哪些连接点上生效。

1
2
3
4
5
6
7
8
public interface Advisor {
Advice EMPTY_ADVICE = new Advice() {
};
// 获取通知
Advice getAdvice();

boolean isPerInstance();
}

InstantiationModelAwarePointcutAdvisorImpl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
final class InstantiationModelAwarePointcutAdvisorImpl implements InstantiationModelAwarePointcutAdvisor, AspectJPrecedenceInformation, Serializable {
private static final Advice EMPTY_ADVICE = new Advice() {
};
// Pointcut - 切入点
private final AspectJExpressionPointcut declaredPointcut;
// 参数信息
private final Class<?> declaringClass;
private final String methodName;
private final Class<?>[] parameterTypes;
// 增强方法
private transient Method aspectJAdviceMethod;
// 用于获取Advisor和Advice的工厂方法
private final AspectJAdvisorFactory aspectJAdvisorFactory;
// 获取AspectMetadata 元数据信息
private final MetadataAwareAspectInstanceFactory aspectInstanceFactory;
private final int declarationOrder;
private final String aspectName;
private final Pointcut pointcut;
private final boolean lazy;
@Nullable
private Advice instantiatedAdvice;
@Nullable
private Boolean isBeforeAdvice;
// AspectJPrecedenceInformation的方法
private Boolean isAfterAdvice;
}

image-20230406092414132

AspectJAdvisorFactory

用于获取Advisor - 通知者和 Advice 通知的工厂

1
2
3
4
5
6
7
8
9
10
11
public interface AspectJAdvisorFactory {
boolean isAspect(Class<?> var1);

void validate(Class<?> var1) throws AopConfigException;
// 获取 Advisor 通过MetadataAwareAspectInstanceFactory
List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory var1);

Advisor getAdvisor(Method var1, MetadataAwareAspectInstanceFactory var2, int var3, String var4);
// 实现类 通过Anotation的类型创建
Advice getAdvice(Method var1, AspectJExpressionPointcut var2, MetadataAwareAspectInstanceFactory var3, int var4, String var5);
}
ReflectiveAspectJAdvisorFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// 
public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFactory implements Serializable {


// 用于创建AspectJAroundAdvice AspectJMethodBeforeAdvice AspectJAfterReturningAdvice
// advice对象
public Advice getAdvice(Method candidateAdviceMethod, AspectJExpressionPointcut expressionPointcut, MetadataAwareAspectInstanceFactory aspectInstanceFactory, int declarationOrder, String aspectName) {
Class<?> candidateAspectClass = aspectInstanceFactory.getAspectMetadata().getAspectClass();
this.validate(candidateAspectClass);
AspectJAnnotation<?> aspectJAnnotation = AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);
if (aspectJAnnotation == null) {
return null;
}
Object springAdvice;
switch(aspectJAnnotation.getAnnotationType()) {
case AtPointcut:
return null;
case AtAround:
springAdvice = new AspectJAroundAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
break;
case AtBefore:
springAdvice = new AspectJMethodBeforeAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
break;
case AtAfter:
springAdvice = new AspectJAfterAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
break;
case AtAfterReturning:
springAdvice = new AspectJAfterReturningAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
AfterReturning afterReturningAnnotation = (AfterReturning)aspectJAnnotation.getAnnotation();
if (StringUtils.hasText(afterReturningAnnotation.returning())) {
((AbstractAspectJAdvice)springAdvice).setReturningName(afterReturningAnnotation.returning());
}
break;
case AtAfterThrowing:
springAdvice = new AspectJAfterThrowingAdvice(candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
AfterThrowing afterThrowingAnnotation = (AfterThrowing)aspectJAnnotation.getAnnotation();
if (StringUtils.hasText(afterThrowingAnnotation.throwing())) {
((AbstractAspectJAdvice)springAdvice).setThrowingName(afterThrowingAnnotation.throwing());
}
break;
default:
throw new UnsupportedOperationException("Unsupported advice type on method: " + candidateAdviceMethod);
}

((AbstractAspectJAdvice)springAdvice).setAspectName(aspectName);
((AbstractAspectJAdvice)springAdvice).setDeclarationOrder(declarationOrder);
String[] argNames = this.parameterNameDiscoverer.getParameterNames(candidateAdviceMethod);
if (argNames != null) {
((AbstractAspectJAdvice)springAdvice).setArgumentNamesFromStringArray(argNames);
}

((AbstractAspectJAdvice)springAdvice).calculateArgumentBindings();
return (Advice)springAdvice;
}
}
}
AspectInstanceFactory

获取Aspect对象的实例对象或者元数据信息(类基本信息)

1
2
3
4
5
6
public interface AspectInstanceFactory extends Ordered {
// 获取 Aspect对象的实例 -- 实例对象
Object getAspectInstance();

ClassLoader getAspectClassLoader();
}

image-20230406112053207

MetadataAwareAspectInstanceFactory
1
2
3
4
5
6
public interface MetadataAwareAspectInstanceFactory extends AspectInstanceFactory {
// 获取AspectMetadata -- 元数据 -- 类基本信息
AspectMetadata getAspectMetadata();
//
Object getAspectCreationMutex();
}
1
2
3
4
5
6
public class AspectMetadata implements Serializable {
private final String aspectName;
private final Class<?> aspectClass;
private transient AjType<?> ajType;
private final Pointcut perClausePointcut;
}

image-20230406113728786

image-20230406085006730

Advised

管理Advisor和Advice,还有被代理对象的Class

Advised(被增强对象):Advised是被增强的目标对象。它是应用切面的对象,切面会在Advised的连接点上执行增强方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public interface TargetClassAware {
@Nullable
Class<?> getTargetClass();
}

public interface Advised extends TargetClassAware {
boolean isFrozen();

boolean isProxyTargetClass();

Class<?>[] getProxiedInterfaces();

boolean isInterfaceProxied(Class<?> var1);

void setTargetSource(TargetSource var1);

TargetSource getTargetSource();

void setExposeProxy(boolean var1);

boolean isExposeProxy();

void setPreFiltered(boolean var1);

boolean isPreFiltered();

Advisor[] getAdvisors();

void addAdvisor(Advisor var1) throws AopConfigException;

void addAdvisor(int var1, Advisor var2) throws AopConfigException;

boolean removeAdvisor(Advisor var1);

void removeAdvisor(int var1) throws AopConfigException;

int indexOf(Advisor var1);

boolean replaceAdvisor(Advisor var1, Advisor var2) throws AopConfigException;

void addAdvice(Advice var1) throws AopConfigException;

void addAdvice(int var1, Advice var2) throws AopConfigException;

boolean removeAdvice(Advice var1);

int indexOf(Advice var1);

String toProxyConfigString();
}

image-20230406115216050

AdvisedSupport

Advised的实现类,管理代理对象的所有参数 Advisor. targerclass,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class AdvisedSupport extends ProxyConfig implements Advised {

/** use serialVersionUID from Spring 2.0 for interoperability. */
private static final long serialVersionUID = 2651364800145442165L;


/**
* Canonical TargetSource when there's no target, and behavior is
* supplied by the advisors.
*/
public static final TargetSource EMPTY_TARGET_SOURCE = EmptyTargetSource.INSTANCE;


/** Package-protected to allow direct access for efficiency. */
TargetSource targetSource = EMPTY_TARGET_SOURCE;

/** Whether the Advisors are already filtered for the specific target class. */
private boolean preFiltered = false;

/** The AdvisorChainFactory to use. */
AdvisorChainFactory advisorChainFactory = new DefaultAdvisorChainFactory();

/** Cache with Method as key and advisor chain List as value. */
private transient Map<MethodCacheKey, List<Object>> methodCache;

/**
* Interfaces to be implemented by the proxy. Held in List to keep the order
* of registration, to create JDK proxy with specified order of interfaces.
*/
private List<Class<?>> interfaces = new ArrayList<>();

/**
* List of Advisors. If an Advice is added, it will be wrapped
* in an Advisor before being added to this List.
*/
private List<Advisor> advisors = new ArrayList<>();

联系Proxy和Advisor,Advice – 即将aspectj的方法切入生成动态代理对象 相联系起来

Advised通过 Pointcut找到切入点,获取切入点的信息,通过ProxyConfig获取代理对象,让Advisor统一调度Advice,调用Advice的增强方法

image-20230406115306753

AspectJProxyFactory
1
2
3
4
5
public class AspectJProxyFactory extends ProxyCreatorSupport {
private static final Map<Class<?>, Object> aspectCache = new ConcurrentHashMap();
// 获取 getAdvisor getAdvice
private final AspectJAdvisorFactory aspectFactory = new ReflectiveAspectJAdvisorFactory();
}

ProxyConfig

配置代理对象 :分为三类AopInfrastructureBean、Advised、Singleton

image-20230406120704728

AopInfrastructureBean

1
2
3
// Aop的基础设施Bean -> 即最基本的框架
public interface AopInfrastructureBean {
}

image-20230406120420212

ProxyProcessorSupport

image-20230404172920442

AbstactAutoProxyCreator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
// 在实例化之前生成代理对象
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
Object cacheKey = this.getCacheKey(beanClass, beanName);
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}

if (this.isInfrastructureClass(beanClass) || this.shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}

TargetSource targetSource = this.getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
}

Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
//
Object proxy = this.createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
} else {
return null;
}
}

public boolean postProcessAfterInstantiation(Object bean, String beanName) {
return true;
}

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
return pvs;
}

public Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean;
}

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return this.wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
}

image-20230404173001921

image-20230404173027368

ScopedProxyFactoryBean

image-20230406120616038

AdvisedSupport

ProxyCreatorSupport

ProxyFactoryBean、ProxyFactory、AspectJProxyFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
public class AdvisedSupport extends ProxyConfig implements Advised {
private static final long serialVersionUID = 2651364800145442165L;

public static final TargetSource EMPTY_TARGET_SOURCE;
// // 持有目标类,可以生成代理对象
TargetSource targetSource;
private boolean preFiltered;
AdvisorChainFactory advisorChainFactory;
private transient Map<AdvisedSupport.MethodCacheKey, List<Object>> methodCache;
private List<Class<?>> interfaces;
private List<Advisor> advisors;
private Advisor[] advisorArray;
}

image-20230406120823535

image-20230406121146203

AbstractSingletonProxyFactoryBean

image-20230406120835618

整体代理类生成逻辑

AopProxyFactory

创建AopProxy代理类

1
2
3
4
5
6
7
8
9
10
11
12
public interface AopProxyFactory {

/**
* Create an {@link AopProxy} for the given AOP configuration.
* @param config the AOP configuration in the form of an
* AdvisedSupport object
* @return the corresponding AOP proxy
* @throws AopConfigException if the configuration is invalid
*/
AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException;

}

DefaultAopProxyFactory

具体说创建代理 AopProxy逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {

private static final long serialVersionUID = 7930414337282325166L;


@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (!NativeDetector.inNativeImage() &&
(config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass) || ClassUtils.isLambdaClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}

TargetClassAware

1
2
3
4
5
6
7
8
9
10
11
public interface TargetClassAware {

/**
* Return the target class behind the implementing object
* (typically a proxy configuration or an actual proxy).
* @return the target Class, or {@code null} if not known
*/
@Nullable
Class<?> getTargetClass();

}

ProxyCreatorSupport

通过具体 factory创建代理 AopProxy

1
2
3
4
5
6
7
8
9
10
public class ProxyCreatorSupport extends AdvisedSupport {

private AopProxyFactory aopProxyFactory;
protected final synchronized AopProxy createAopProxy() {
if (!this.active) {
activate();
}
return getAopProxyFactory().createAopProxy(this);
}
}

Advised \ AdvisedSupport – 总领

1
2
3
4
5
6
7
8
9
10
11
12
13
在Spring AOP中,选择代理的类是`AdvisedSupport`。`AdvisedSupport`是Spring AOP框架中的一个核心类,用于存储AOP代理的相关配置信息。

`AdvisedSupport`类中包含了以下重要的属性:

- `TargetSource`:目标对象的信息,包括目标对象本身和目标对象的类型。
- `MethodInterceptor`:拦截器对象,用于执行增强逻辑。
- `MethodMatcher`:方法匹配器,用于匹配需要拦截的方法。
- `Advisor`:通知器对象,包含了拦截器和方法匹配器。
- `ProxyFactory`:代理工厂对象,用于创建代理对象。

通过配置`AdvisedSupport`对象的属性,可以选择使用JDK动态代理还是CGLib动态代理,并指定拦截器、方法匹配器等,从而实现对目标对象的代理。

需要注意的是,`AdvisedSupport`类是Spring AOP框架的内部类,一般不需要直接使用它。在使用Spring AOP时,你可以通过配置XML文件或使用注解来配置AOP相关的信息,Spring框架会自动创建和管理`AdvisedSupport`对象。

管理创建代理、执行代理的 总逻辑、并提供配置信息

image-20230712082954049

AopProxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public interface AopProxy {

/**
* Create a new proxy object.
* <p>Uses the AopProxy's default class loader (if necessary for proxy creation):
* usually, the thread context class loader.
* @return the new proxy object (never {@code null})
* @see Thread#getContextClassLoader()
*/
Object getProxy();

/**
* Create a new proxy object.
* <p>Uses the given class loader (if necessary for proxy creation).
* {@code null} will simply be passed down and thus lead to the low-level
* proxy facility's default, which is usually different from the default chosen
* by the AopProxy implementation's {@link #getProxy()} method.
* @param classLoader the class loader to create the proxy with
* (or {@code null} for the low-level proxy facility's default)
* @return the new proxy object (never {@code null})
*/
Object getProxy(@Nullable ClassLoader classLoader);



}



JdkDynamicAopProxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {

/** Config used to configure this proxy. */
private final AdvisedSupport advised;
@Override
public Object getProxy() {
return getProxy(ClassUtils.getDefaultClassLoader());
}

@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}
}

CglibAopProxy

根据AdvisedSupport 提供的配置信息, 创建Cglib代理的逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class CglibAopProxy implements AopProxy, Serializable {

// Constants for CGLIB callback array indices
private static final int AOP_PROXY = 0;
private static final int INVOKE_TARGET = 1;
private static final int NO_OVERRIDE = 2;
private static final int DISPATCH_TARGET = 3;
private static final int DISPATCH_ADVISED = 4;
private static final int INVOKE_EQUALS = 5;
private static final int INVOKE_HASHCODE = 6;


/** Logger available to subclasses; static to optimize serialization. */
protected static final Log logger = LogFactory.getLog(CglibAopProxy.class);

/** Keeps track of the Classes that we have validated for final methods. */
private static final Map<Class<?>, Boolean> validatedClasses = new WeakHashMap<>();


/** The configuration used to configure this proxy. */
protected final AdvisedSupport advised;
@Override
public Object getProxy() {
return getProxy(null);
}

@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
}

try {
Class<?> rootClass = this.advised.getTargetClass();
Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

Class<?> proxySuperClass = rootClass;
if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
proxySuperClass = rootClass.getSuperclass();
Class<?>[] additionalInterfaces = rootClass.getInterfaces();
for (Class<?> additionalInterface : additionalInterfaces) {
this.advised.addInterface(additionalInterface);
}
}

// Validate the class, writing log messages as necessary.
validateClassIfNecessary(proxySuperClass, classLoader);

// Configure CGLIB Enhancer...
Enhancer enhancer = createEnhancer();
if (classLoader != null) {
enhancer.setClassLoader(classLoader);
if (classLoader instanceof SmartClassLoader &&
((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
enhancer.setUseCache(false);
}
}
enhancer.setSuperclass(proxySuperClass);
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));

Callback[] callbacks = getCallbacks(rootClass);
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
// fixedInterceptorMap only populated at this point, after getCallbacks call above
enhancer.setCallbackFilter(new ProxyCallbackFilter(
this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types);

// Generate the proxy class and create a proxy instance.
return createProxyClassAndInstance(enhancer, callbacks);
}
catch (CodeGenerationException | IllegalArgumentException ex) {
throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
": Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (Throwable ex) {
// TargetSource.getTarget() failed
throw new AopConfigException("Unexpected AOP exception", ex);
}
}
}

image-20230712083639599

PropertySource加载

PropertySource

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public abstract class PropertySource<T> {
protected final String name;
// InputStreanSource子类 -- 包括各种格式Resource
// 这里是 EncodeResource
protected final T source;
}
// Iterable -- 用于遍历等操作PropertySource
public interface PropertySources extends Iterable<PropertySource<?>> {
// 流式操作
default Stream<PropertySource<?>> stream() {
return StreamSupport.stream(spliterator(), false);
}
boolean contains(String name);
PropertySource<?> get(String name);

}

image-20230416162221630

image-20230416162125168

PropertySourceFactory

1
2
3
4
5
public interface PropertySourceFactory {

PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException;

}

DefaultPropertySourceFactory

1
2
3
4
5
6
7
public class DefaultPropertySourceFactory implements PropertySourceFactory {

@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
return (name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource));
}
}

InputStreamSource

1
2
3
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}

EncodedResource

1
2
3
4
5
6
7
8
// 封装 编码
public class EncodedResource implements InputStreamSource {
private final Resource resource;
@Nullable
private final String encoding;
@Nullable
private final Charset charset;
}

Resource

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/* @see #getInputStream()
* @see #getURL()
* @see #getURI()
* @see #getFile()
* @see WritableResource
* @see ContextResource
* @see UrlResource
* @see FileUrlResource
* @see FileSystemResource
* @see ClassPathResource
* @see ByteArrayResource
* @see InputStreamResource
*/
public interface Resource extends InputStreamSource {

}

BeanDefinition加载

配置类加载

配置类ConfigurationClass的BeanDefinition注册和解析

流程:

通过注解或者方法实现,创建配置类

0、ConfigurationClassPost 获取对应的 condidate(判断是否满足ConfigurationClass条件)的 BeanDefinition ,

1、调用 ConfigurationClassParse的parse()方法,将其解析 - 封装为ConfigurationClass对象,

2、调用ConfigurationClassBeanDefinitionReader的loadBeanDefinition()方法,将ConfigurationClass对象加载为BeanDefinition对象注册到BeanFactory中

ConfiguratonClass可以获取 BeanMethod(方法上有@Bean)注解

1
2
3
4
5
6
7
8
9
10
11
12
SpringApplication.run()
=>refreshContext(ConfigurableApplicationContext context)
=> EmbeddedWebApplicationContext.refresh()
=> AbstractApplicationContext.refresh()
=>invokeBeanFactoryPostProcessors()
=> PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()
=> ConfigurationClassPostProcessor.processConfigBeanDefinitions()
=> ConfigurationClassParse.parse()
=> ConfigurationClassBeanDefinitionReader.loadBeanDefinitions()

调用ConfigurationClassPostProcessor创世纪后置处理器的时候,肯定是先调用带注册功能的BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法对配置类的Bean定义进行处理,然后再调用BeanFactoryPostProcessor接口的postProcessBeanFactory方法进行注册;

PostProcessorRegistrationDelegate

invokeBeanFactoryPostProcessors () :

​ 1、初始化 ConfigurationClasPostProcessor 类 并 调用 possProcessor()方法 - 用于解析配置类信息

​ 2、 执行其他postProcessor()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
final class PostProcessorRegistrationDelegate {
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22

// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();

if (beanFactory instanceof BeanDefinitionRegistry registry) {
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor registryProcessor) {
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}

// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

// PriorityOrdered 实现该接口的 BeanDefinitionRegistryPostProcessors 优先级最高 限制性
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// getBean() 显示创建 ConfigurationClassPostProcessor实例
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 对 registerProcessor进行排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 优先调用postProcessBeanDefinitionRegistry
// 调用 registerProcessor的 postProcessBeanDefinitionRegistry()
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();

//
// Ordered 实现该接口的 BeanDefinitionRegistryPostProcessors 较后执行
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
// getBean() 根据AnnotatedBeanDefinitionReader注册的 BeanDefinition创建实列
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
//
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();

// 最后执行 普通的BeanDefinitionRegistryPostProcessors
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
}

// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}

else {
// 执行容器的实例
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}

// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}

// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22

String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 实例化 BeanPostProcessor
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 分多个等级注册 PriorityOrdered, Ordered, regular(常规), internal BeanPostProcessors

// First, register the BeanPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

// Next, register the BeanPostProcessors that implement Ordered.
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);

// Now, register all regular BeanPostProcessors.
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

// Finally, re-register all internal BeanPostProcessors.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);

// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
}

ConfigurationClassPostProcessor

image-20230723172702175

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// 通过实现各种Aware接口获取解析所需要的属性
public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware {

// 方法invokeBeanFactoryPostProcessors() ## postProcessBeanFactory()
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
int factoryId = System.identityHashCode(beanFactory);
if (this.factoriesPostProcessed.contains(factoryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + beanFactory);
}
this.factoriesPostProcessed.add(factoryId);
if (!this.registriesPostProcessed.contains(factoryId)) {
// BeanDefinitionRegistryPostProcessor hook apparently not supported...
// Simply call processConfigurationClasses lazily at this point then.
// 调用创建 ConfigurationClass
processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
}

enhanceConfigurationClasses(beanFactory);
beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
}

// 配置类 信息(@Bean)解析为 BeanDefinition
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
// 获取当前 上下文可能为 Configuration的beanName用于下面的解析操作
// 配置类信息 再 AnnotatedBeanDefinitionReader的 doRegister() 处进行beanDefinition注册
// 通过 ConfigurableListableBeanFactory --》 BeanDefinitionRegistry -》 获取candidateNames
// 获取已经注册的BeanName === BeanDefinition在 obtainBeanFactory()的方法内
// 调用loadBeanDefinition() 方法进行注册
String[] candidateNames = registry.getBeanDefinitionNames();

for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
// 通过 ji
// ConfigurationClass
// Check whether the given bean definition is a candidate for a configuration class
// 检查是否满足 配置类候选者 条件
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}

// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {
return;
}

// Sort by previously determined @Order value, if applicable
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});

// Detect any custom bean name generation strategy supplied through the enclosing application context
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry _sbr) {
sbr = _sbr;
if (!this.localBeanNameGeneratorSet) {
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
if (generator != null) {
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}

if (this.environment == null) {
this.environment = new StandardEnvironment();
}
// 初始化 ConfigurationClassParser
// Parse each @Configuration class -- 解析@Configuration注解的Class
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);

Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
// 调用 parser.parse()
parser.parse(candidates);
parser.validate();

Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);

// Read the model and create bean definitions based on its content
// 读取模式,并基于ConfigurationClass信息创建beanDefinition
if (this.reader == null) {
// 初始化 ConfigurationClassBeanDefinitionReader
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
// 调用reader.loadBeanDefinitions()
// 将configClasses注册为BeanDefinition
// 加载BeanDefinition -》
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();

candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = Set.of(candidateNames);
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());

// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}

// Store the PropertySourceDescriptors to contribute them Ahead-of-time if necessary
this.propertySourceDescriptors = parser.getPropertySourceDescriptors();

if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory cachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
cachingMetadataReaderFactory.clearCache();
}
}
}

image-20230412112047479

ConfigurationClassParser

深入理解Spring的ImportSelector接口 - 聂晨 - 博客园 (cnblogs.com)

解析@Configuration的Class

1
2
3
4
5
// Component,ComponentScan,Import,ImportResource注解和Bean方法注解就是配置类
// 流程
1、component注解,会在Context初始化时,调用AnnotatedBeanDefinitionReader进行解析注册为BeanDefinition
2、再ConfigurationClassParser中进行 parse,即解析配置类信息,封装为 ConfigurationClass对象,
3、解析

(10条消息) Spring 5.x 源码之旅七ConfigurationClassParser解析配置类_王伟王胖胖的博客-CSDN博客

在这里插入图片描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
class ConfigurationClassParser {
// 解析ConfigurationBeanDefinition,即解析Configuratione的各种信息
public void parse(Set<BeanDefinitionHolder> configCandidates) {
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
try { // 注解AnnotatedBeanDefinition
if (bd instanceof AnnotatedBeanDefinition annotatedBeanDef) {
parse(annotatedBeanDef.getMetadata(), holder.getBeanName());
} // AbstractBeanDefinition
else if (bd instanceof AbstractBeanDefinition abstractBeanDef && abstractBeanDef.hasBeanClass()) {
parse(abstractBeanDef.getBeanClass(), holder.getBeanName());
}
else {
parse(bd.getBeanClassName(), holder.getBeanName());
}
}
}
//
this.deferredImportSelectorHandler.process();
}

// 通过 类路径获取 MetadataReader,创建ConfigurationClass
protected final void parse(@Nullable String className, String beanName) throws IOException {
Assert.notNull(className, "No bean class name for configuration class bean definition");
MetadataReader reader = this.metadataReaderFactory.getMetadataReader(className);
processConfigurationClass(new ConfigurationClass(reader, beanName), DEFAULT_EXCLUSION_FILTER);
}
// 通过Class对象直接创建 ConfigurationClass
protected final void parse(Class<?> clazz, String beanName) throws IOException {
// 创建 ConfigurationClass对象
processConfigurationClass(new ConfigurationClass(clazz, beanName), DEFAULT_EXCLUSION_FILTER);
}

// 通过注解信息 创建ConfigurationClass
protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
}

@Nullable
protected final SourceClass doProcessConfigurationClass(
ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
throws IOException {

if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass, filter);
}

// Process any @PropertySource annotations
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.propertySourceRegistry != null) {
this.propertySourceRegistry.processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}

// Process any @ComponentScan annotations
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// Check the set of scanned definitions for any further config classes and parse recursively if needed
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
// 关键 -- 自动注入 -- 实现接口,方法调用
// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}

// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}

// Process default methods on interfaces
processInterfaces(configClass, sourceClass);

// Process superclass, if any
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
return sourceClass.getSuperClass();
}
}

// No superclass -> processing is complete
return null;
}

// 递归解析 import的信息
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
boolean checkForCircularImports) {

if (importCandidates.isEmpty()) {
return;
}

if (checkForCircularImports && isChainedImportOnStack(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try { //
for (SourceClass candidate : importCandidates) {
// 配置类是一个 ImportSelector
if (candidate.isAssignable(ImportSelector.class)) {
// Candidate class is an ImportSelector -> delegate to it to determine imports
// 委托 导入 Imports
Class<?> candidateClass = candidate.loadClass();
// 实例化 当前的 ImportSelector接口实现类 ---autoConfiguraitonImportSelector就是在这实例化
ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
this.environment, this.resourceLoader, this.registry);
Predicate<String> selectorFilter = selector.getExclusionFilter();
// 过滤
if (selectorFilter != null) {
exclusionFilter = exclusionFilter.or(selectorFilter);
} /////如果为延迟导入处理则加入集合当中
if (selector instanceof DeferredImportSelector deferredImportSelector) {
this.deferredImportSelectorHandler.handle(configClass, deferredImportSelector);
}
else {// 调用selectImports方法,获取需要导入的 类的全路径信息
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
// 封装
Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
// 递归调用
processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
}
} // ImportBeanDefinitionRegistrar接口 解析调用
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
// Candidate class is an ImportBeanDefinitionRegistrar ->
// delegate to it to register additional bean definitions
Class<?> candidateClass = candidate.loadClass();
ImportBeanDefinitionRegistrar registrar =
ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
this.environment, this.resourceLoader, this.registry);
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
}
else { // 如果都不是, 则认为是一个配置类,调用配置类解析方法解析
// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
// process it as an @Configuration class
// 如果当前的类既不是ImportSelector也不是ImportBeanDefinitionRegistar就进行@Configuration的解析处理
this.importStack.registerImport(
currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
// 当作配置类进行处理
processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
}
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to process import candidates for configuration class [" +
configClass.getMetadata().getClassName() + "]: " + ex.getMessage(), ex);
}
finally {
this.importStack.pop();
}
}
}
}

ImportResource

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*Indicates one or more resources containing bean definitions to import*/
// 导入 BeanDefinition资源
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ImportResource {

/**
* Alias for {@link #locations}.
* @see #locations
* @see #reader
*/
@AliasFor("locations")
String[] value() default {};

/**
* Resource locations from which to import.
* <p>Supports resource-loading prefixes such as {@code classpath:},
* {@code file:}, etc.
* <p>Consult the Javadoc for {@link #reader} for details on how resources
* will be processed.
* @since 4.2
* @see #value
* @see #reader
*/
@AliasFor("value")
String[] locations() default {};

/**
* {@link BeanDefinitionReader} implementation to use when processing
* resources specified via the {@link #value} attribute.
* <p>By default, the reader will be adapted to the resource path specified:
* {@code ".groovy"} files will be processed with a
* {@link org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader GroovyBeanDefinitionReader};
* whereas, all other resources will be processed with an
* {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader XmlBeanDefinitionReader}.
* @see #value
*/
Class<? extends BeanDefinitionReader> reader() default BeanDefinitionReader.class;

}

ImportSelector

获取需要导入的 BeanDefinition全路径信息,当作 ConfigurationClass来解析

1
2
3
4
5
6
7
public interface ImportSelector {
String[] selectImports(AnnotationMetadata importingClassMetadata);
@Nullable
default Predicate<String> getExclusionFilter() {
return null;
}
}

ImportRegistry

1
2
3
4
5
6
7
8
interface ImportRegistry {

@Nullable
AnnotationMetadata getImportingClassFor(String importedClass);

void removeImportingClass(String importingClass);

}

ConfigurationClass

配置类的信息封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
final class ConfigurationClass {

private final AnnotationMetadata metadata;

private final Resource resource;

@Nullable
private String beanName;

private final Set<ConfigurationClass> importedBy = new LinkedHashSet<>(1);

private final Set<BeanMethod> beanMethods = new LinkedHashSet<>();

private final Map<String, Class<? extends BeanDefinitionReader>> importedResources =
new LinkedHashMap<>();

private final Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> importBeanDefinitionRegistrars =
new LinkedHashMap<>();

final Set<String> skippedBeanMethods = new HashSet<>();
}

ConfigurationClassBeanDefinitionReader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
读取一组已经被完整解析的配置类ConfigurationClass,向给定bean容器BeanDefinitionRegistry注册其中所有的bean定义。

该内部工具由Spring BeanDefinitionRegistryPostProcessor ConfigurationClassParser使用。在容器启动过程中, ConfigurationClassParser会在BeanDefinitionRegistryPostProcessor 应用阶段被调用,用于发现应用中所有的配置类ConfigurationClass,然后交给ConfigurationClassBeanDefinitionReader将这些配置类中的bean定义注册到容器

SpringApplication.run()
=>refreshContext(ConfigurableApplicationContext context)
=> EmbeddedWebApplicationContext.refresh()
=> AbstractApplicationContext.refresh()
=>invokeBeanFactoryPostProcessors()
=> PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()
=> ConfigurationClassPostProcessor.processConfigBeanDefinitions()
// 加载 ConfiguraitonClass 为 BeanDefinition
=> ConfigurationClassBeanDefinitionReader.loadBeanDefinitions()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class ConfigurationClassBeanDefinitionReader {

private static final Log logger = LogFactory.getLog(ConfigurationClassBeanDefinitionReader.class);

private static final ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();

private final BeanDefinitionRegistry registry;

private final SourceExtractor sourceExtractor;

private final ResourceLoader resourceLoader;

private final Environment environment;

private final BeanNameGenerator importBeanNameGenerator;

private final ImportRegistry importRegistry;
// 对@Conditional注解求值的工具类
private final ConditionEvaluator conditionEvaluator;

// 读取一组已经被完整解析的配置类ConfigurationClass,向给定bean容器BeanDefinitionRegistry注册其中所有的bean定义。
public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();
// 遍历当前 ConfigurationClass
for (ConfigurationClass configClass : configurationModel) {
loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
}
}

/**
* Read a particular {@link ConfigurationClass}, registering bean definitions
* for the class itself and all of its {@link Bean} methods.
*/
private void loadBeanDefinitionsForConfigurationClass(
ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {

// 如果 条件Condition判断 应当跳过当前配置类,则从当前registry中移除 BeanDefinition信息
if (trackedConditionEvaluator.shouldSkip(configClass)) {
String beanName = configClass.getBeanName();
if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {
this.registry.removeBeanDefinition(beanName);
}
this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());
return;
}

if (configClass.isImported()) {
// 如果已经导入,
registerBeanDefinitionForImportedConfigurationClass(configClass);
}
// 遍历configClass的 BeanMethod (@Bean注解信息),加载为BeanDefinition
for (BeanMethod beanMethod : configClass.getBeanMethods()) {
loadBeanDefinitionsForBeanMethod(beanMethod);
}
// 参数:Map<String, Class<? extends BeanDefinitionReader>>
// ImportResource 的 ConfigClass
loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
// 参数:Map<ImportBeanDefinitionRegistrar, AnnotationMetadata>
// ImportBeanDefinitionRegistrars 的 ConfigClass
loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
}
}

AdviceModeImportSelector

1
2
3
4
5
6
7
8
9
public abstract class AdviceModeImportSelector<A extends Annotation> implements ImportSelector {

/**
* The default advice mode attribute name.
*/
public static final String DEFAULT_ADVICE_MODE_ATTRIBUTE_NAME = "mode";
// 根据 AdviceModle返回需要Import的类的全限定名
protected abstract String[] selectImports(AdviceMode adviceMode);
}
1
2
3
4
5
6
7
8
9
10
11
12
public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {

private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME =
"org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";

public String[] selectImports(AdviceMode adviceMode) {
return switch (adviceMode) {
case PROXY -> new String[] {ProxyAsyncConfiguration.class.getName()};
case ASPECTJ -> new String[] {ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME};
};
}
}

image-20230410152227214

Transaction模块

BeanDefinition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package org.springframework.transaction;

import org.springframework.lang.Nullable;

/**
* Interface that defines Spring-compliant transaction properties.
* Based on the propagation behavior definitions analogous to EJB CMT attributes.
*
* <p>Note that isolation level and timeout settings will not get applied unless
* an actual new transaction gets started. As only {@link #PROPAGATION_REQUIRED},
* {@link #PROPAGATION_REQUIRES_NEW}, and {@link #PROPAGATION_NESTED} can cause
* that, it usually doesn't make sense to specify those settings in other cases.
* Furthermore, be aware that not all transaction managers will support those
* advanced features and thus might throw corresponding exceptions when given
* non-default values.
*
* <p>The {@linkplain #isReadOnly() read-only flag} applies to any transaction context,
* whether backed by an actual resource transaction or operating non-transactionally
* at the resource level. In the latter case, the flag will only apply to managed
* resources within the application, such as a Hibernate {@code Session}.

* @see PlatformTransactionManager#getTransaction(TransactionDefinition)
* @see org.springframework.transaction.support.DefaultTransactionDefinition
* @see org.springframework.transaction.interceptor.TransactionAttribute
*/
public interface TransactionDefinition {

/**
* Support a current transaction; create a new one if none exists.
* Analogous to the EJB transaction attribute of the same name.
* <p>This is typically the default setting of a transaction definition
* and typically defines a transaction synchronization scope.
*/
int PROPAGATION_REQUIRED = 0;

/**
* Support a current transaction; execute non-transactionally if none exists.
* Analogous to the EJB transaction attribute of the same name.
* <p><b>NOTE:</b> For transaction managers with transaction synchronization,
* {@code PROPAGATION_SUPPORTS} is slightly different from no transaction
* at all, as it defines a transaction scope that synchronization might apply to.
* As a consequence, the same resources (a JDBC {@code Connection}, a
* Hibernate {@code Session}, etc) will be shared for the entire specified
* scope. Note that the exact behavior depends on the actual synchronization
* configuration of the transaction manager.
* <p>In general, use {@code PROPAGATION_SUPPORTS} with care. In particular, do
* not rely on {@code PROPAGATION_REQUIRED} or {@code PROPAGATION_REQUIRES_NEW}
* <i>within</i> a {@code PROPAGATION_SUPPORTS} scope (which may lead to
* synchronization conflicts at runtime). If such nesting is unavoidable, make sure
* to configure your transaction manager appropriately (typically switching to
* "synchronization on actual transaction").
* @see org.springframework.transaction.support.AbstractPlatformTransactionManager#setTransactionSynchronization
* @see org.springframework.transaction.support.AbstractPlatformTransactionManager#SYNCHRONIZATION_ON_ACTUAL_TRANSACTION
*/
int PROPAGATION_SUPPORTS = 1;

/**
* Support a current transaction; throw an exception if no current transaction
* exists. Analogous to the EJB transaction attribute of the same name.
* <p>Note that transaction synchronization within a {@code PROPAGATION_MANDATORY}
* scope will always be driven by the surrounding transaction.
*/
int PROPAGATION_MANDATORY = 2;

/**
* Create a new transaction, suspending the current transaction if one exists.
* Analogous to the EJB transaction attribute of the same name.
* <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box
* on all transaction managers. This in particular applies to
* {@link org.springframework.transaction.jta.JtaTransactionManager},
* which requires the {@code jakarta.transaction.TransactionManager} to be
* made available to it (which is server-specific in standard Jakarta EE).
* <p>A {@code PROPAGATION_REQUIRES_NEW} scope always defines its own
* transaction synchronizations. Existing synchronizations will be suspended
* and resumed appropriately.
* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager
*/
int PROPAGATION_REQUIRES_NEW = 3;

/**
* Do not support a current transaction; rather always execute non-transactionally.
* Analogous to the EJB transaction attribute of the same name.
* <p><b>NOTE:</b> Actual transaction suspension will not work out-of-the-box
* on all transaction managers. This in particular applies to
* {@link org.springframework.transaction.jta.JtaTransactionManager},
* which requires the {@code jakarta.transaction.TransactionManager} to be
* made available to it (which is server-specific in standard Jakarta EE).
* <p>Note that transaction synchronization is <i>not</i> available within a
* {@code PROPAGATION_NOT_SUPPORTED} scope. Existing synchronizations
* will be suspended and resumed appropriately.
* @see org.springframework.transaction.jta.JtaTransactionManager#setTransactionManager
*/
int PROPAGATION_NOT_SUPPORTED = 4;

/**
* Do not support a current transaction; throw an exception if a current transaction
* exists. Analogous to the EJB transaction attribute of the same name.
* <p>Note that transaction synchronization is <i>not</i> available within a
* {@code PROPAGATION_NEVER} scope.
*/
int PROPAGATION_NEVER = 5;

// 嵌套
int PROPAGATION_NESTED = 6;

// 隔离级别
/* 数据库默认隔离级别 -- 根据 java.sql.Connection*/
int ISOLATION_DEFAULT = -1;

int ISOLATION_READ_UNCOMMITTED = 1; // same as java.sql.Connection.TRANSACTION_READ_UNCOMMITTED;

int ISOLATION_READ_COMMITTED = 2; // same as java.sql.Connection.TRANSACTION_READ_COMMITTED;

int ISOLATION_REPEATABLE_READ = 4; // same as java.sql.Connection.TRANSACTION_REPEATABLE_READ;

int ISOLATION_SERIALIZABLE = 8; // same as java.sql.Connection.TRANSACTION_SERIALIZABLE;


/**
* Use the default timeout of the underlying transaction system,
* or none if timeouts are not supported.
*/
int TIMEOUT_DEFAULT = -1;


/**
* Return the propagation behavior.
* <p>Must return one of the {@code PROPAGATION_XXX} constants
* defined on {@link TransactionDefinition this interface}.
* <p>The default is {@link #PROPAGATION_REQUIRED}.
* @return the propagation behavior
* @see #PROPAGATION_REQUIRED
* @see org.springframework.transaction.support.TransactionSynchronizationManager#isActualTransactionActive()
*/
default int getPropagationBehavior() {
return PROPAGATION_REQUIRED;
}

/**
* Return the isolation level.
* <p>Must return one of the {@code ISOLATION_XXX} constants defined on
* {@link TransactionDefinition this interface}. Those constants are designed
* to match the values of the same constants on {@link java.sql.Connection}.
* <p>Exclusively designed for use with {@link #PROPAGATION_REQUIRED} or
* {@link #PROPAGATION_REQUIRES_NEW} since it only applies to newly started
* transactions. Consider switching the "validateExistingTransactions" flag to
* "true" on your transaction manager if you'd like isolation level declarations
* to get rejected when participating in an existing transaction with a different
* isolation level.
* <p>The default is {@link #ISOLATION_DEFAULT}. Note that a transaction manager
* that does not support custom isolation levels will throw an exception when
* given any other level than {@link #ISOLATION_DEFAULT}.
* @return the isolation level
* @see #ISOLATION_DEFAULT
* @see org.springframework.transaction.support.AbstractPlatformTransactionManager#setValidateExistingTransaction
*/
default int getIsolationLevel() {
return ISOLATION_DEFAULT;
}

/**
* Return the transaction timeout.
* <p>Must return a number of seconds, or {@link #TIMEOUT_DEFAULT}.
* <p>Exclusively designed for use with {@link #PROPAGATION_REQUIRED} or
* {@link #PROPAGATION_REQUIRES_NEW} since it only applies to newly started
* transactions.
* <p>Note that a transaction manager that does not support timeouts will throw
* an exception when given any other timeout than {@link #TIMEOUT_DEFAULT}.
* <p>The default is {@link #TIMEOUT_DEFAULT}.
* @return the transaction timeout
*/
default int getTimeout() {
return TIMEOUT_DEFAULT;
}

/**
* Return whether to optimize as a read-only transaction.
* <p>The read-only flag applies to any transaction context, whether backed
* by an actual resource transaction ({@link #PROPAGATION_REQUIRED}/
* {@link #PROPAGATION_REQUIRES_NEW}) or operating non-transactionally at
* the resource level ({@link #PROPAGATION_SUPPORTS}). In the latter case,
* the flag will only apply to managed resources within the application,
* such as a Hibernate {@code Session}.
* <p>This just serves as a hint for the actual transaction subsystem;
* it will <i>not necessarily</i> cause failure of write access attempts.
* A transaction manager which cannot interpret the read-only hint will
* <i>not</i> throw an exception when asked for a read-only transaction.
* @return {@code true} if the transaction is to be optimized as read-only
* ({@code false} by default)
* @see org.springframework.transaction.support.TransactionSynchronization#beforeCommit(boolean)
* @see org.springframework.transaction.support.TransactionSynchronizationManager#isCurrentTransactionReadOnly()
*/
default boolean isReadOnly() {
return false;
}

/**
* Return the name of this transaction. Can be {@code null}.
* <p>This will be used as the transaction name to be shown in a
* transaction monitor, if applicable (for example, WebLogic's).
* <p>In case of Spring's declarative transactions, the exposed name will be
* the {@code fully-qualified class name + "." + method name} (by default).
* @return the name of this transaction ({@code null} by default}
* @see org.springframework.transaction.interceptor.TransactionAspectSupport
* @see org.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionName()
*/
@Nullable
default String getName() {
return null;
}


// Static builder methods

/**
* Return an unmodifiable {@code TransactionDefinition} with defaults.
*/
static TransactionDefinition withDefaults() {
return StaticTransactionDefinition.INSTANCE;
}

}

1
2
3
4
5
6
7
8
// since spring 5.2
public interface PlatformTransactionManager extends TransactionManager {
TransactionStatus getTransaction(@Nullable TransactionDefinition var1) throws TransactionException;

void commit(TransactionStatus var1) throws TransactionException;

void rollback(TransactionStatus var1) throws TransactionException;
}

image-20230410171445188

Aware

通过实现Aware接口,可以在对应的资源创建后,获取到对应的资源

例如:

BeanFactoryAware

1
2
3
public interface BeanFactoryAware extends Aware {
void setBeanFactory(BeanFactory var1) throws BeansException;
}

image-20230406233747409

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Aware (org.springframework.beans.factory)
//
ApplicationEventPublisherAware (org.springframework.context)
//
ServletContextAware (org.springframework.web.context)
//
MessageSourceAware (org.springframework.context)
ResourceLoaderAware (org.springframework.context)
NotificationPublisherAware (org.springframework.jmx.export.notification)
EnvironmentAware (org.springframework.context)
BeanFactoryAware (org.springframework.beans.factory)
EmbeddedValueResolverAware (org.springframework.context)
ImportAware (org.springframework.context.annotation)
ServletConfigAware (org.springframework.web.context)
LoadTimeWeaverAware (org.springframework.context.weaving)
BeanNameAware (org.springframework.beans.factory)
BeanClassLoaderAware (org.springframework.beans.factory)
ApplicationContextAware (org.springframework.context)

Listener

AbstractApplicationContext的使用s

1
2
3
4
5
6
7
8
9
10
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
// 广播器
private ApplicationEventMulticaster applicationEventMulticaster;
// 监听者
private final Set<ApplicationListener<?>> applicationListeners;
//
private Set<ApplicationListener<?>> earlyApplicationListeners;
// 监听事件
private Set<ApplicationEvent> earlyApplicationEvents;
}

ApplicationEventMulticaster

管理EventListener和Event,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public interface ApplicationEventMulticaster {
void addApplicationListener(ApplicationListener<?> var1);

void addApplicationListenerBean(String var1);

void removeApplicationListener(ApplicationListener<?> var1);

void removeApplicationListenerBean(String var1);

void removeAllListeners();

void multicastEvent(ApplicationEvent var1);

void multicastEvent(ApplicationEvent var1, @Nullable ResolvableType var2);
}

EventListener

image-20230406234800354

ApplicationListener

1
2
3
4
5
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
// 绑定监听事件
void onApplicationEvent(E var1);
}

SpringApplicationRunListener

事件发布,通过事件接口,能够收到消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public interface SpringApplicationRunListener {
default void starting() {
}

default void environmentPrepared(ConfigurableEnvironment environment) {
}

default void contextPrepared(ConfigurableApplicationContext context) {
}

default void contextLoaded(ConfigurableApplicationContext context) {
}

default void started(ConfigurableApplicationContext context) {
}

default void running(ConfigurableApplicationContext context) {
}

default void failed(ConfigurableApplicationContext context, Throwable exception) {
}
}

EventObject

定义事件

image-20230406235010626

SpringApplicationEvent

事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public abstract class SpringApplicationEvent extends ApplicationEvent {
private final String[] args;

public SpringApplicationEvent(SpringApplication application, String[] args) {
super(application);
this.args = args;
}

public SpringApplication getSpringApplication() {
return (SpringApplication)this.getSource();
}

public final String[] getArgs() {
return this.args;
}
}

image-20230406234346965

注解

元注解

@Target

@Retention

Spring注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
@Autowired
@Qualifier
@Value("")

// CommonAnnotationBeanPostProssor
// Method 用于 一个单例bean需要和一个非单例bean组合使用或者一个非单例bean和另一个非单例bean组合使用时创建原型对象 -- 而不是单例对象
@Lookup
对于@Lookup修饰的方法,有相对应的标准
<public|protected> [abstract] <return-type> theMethodName(no-arguments);

@Resource
1
2
3
4
5
6
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@Caching
@Cacheable

Scheduling - 调度注解

1
2
3
4
5
6
import org.springframework.scheduling.annotation.*
@EnableScheduling
@Scheduled
@Schedules()
@EnableAsync
@Async

stereotype - 定型注解

1
2
3
4
5
6
import org.springframework.stereotype.*;
@Component
@Controller
@Indexed
@Repository
@Service

Context - 上下文注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import org.springframework.context.annotation
@Bean
@ComponentScan
@ComponentScans(value = {})
@Conditional(value = Condition.class)
@Configuration
@DependsOn
@EnableAspectJAutoProxy
@EnableLoadTimeWeaving
@EnableMBeanExport
@Import(value = Test1.class)
@Lazy
@Primary
@PropertySource(value = "")
@PropertySources(value = {})
@Profile(value = {})
@Role(value = 1)
@Scope

Autowired - 自动注入注解

1
2
3
4
5
6
7
8
import org.springframework.boot.autoconfigure.*;
@AutoConfigurationPackage
@AutoConfigureAfter
@AutoConfigureBefore
@AutoConfigureOrder
@EnableAutoConfiguration
@ImportAutoConfiguration
@SpringBootApplication

Properties 配置注解

1
2
3
4
5
6
7
8
import org.springframework.boot.context.properties.*;
@ConfigurationProperties
@ConfigurationPropertiesBinding
@ConfigurationPropertiesScan
@ConstructorBinding
@DeprecatedConfigurationProperty
@EnableConfigurationProperties
@NestedConfigurationProperty

SPI 接口 Service Provider Interface

ApplicationContextInitializer

1
2
3
4
5
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {
// 实现接口进行初始化,再SpringApplication中设置属性
// 在SpringApplication##run() ### prepareContext()方法中调用
void initialize(C var1);
}

拓展点

1、 AbstractApplicationContext ## prepareRefresh() ## initPropertySources()

2、

SPI 文件

spring.factory:可以通过SpringFactoryLoader通过类的全路径进行加载注入

spring.provides: 能够引入填写依赖

1
provides: spring-security-web,spring-security-config

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
```







# 初始化

启动时实例化类 - SingletonObjects

```json
// Initializer接口
"org.springframework.boot.context.ContextIdApplicationContextInitializer$ContextId" -> {ContextIdApplicationContextInitializer$ContextId@1992}
"autoConfigurationReport" -> {ConditionEvaluationReport@2549}
// 封装Argument
"springApplicationArguments" -> {DefaultApplicationArguments@2399}
"springBootLoggingSystem" -> {LogbackLoggingSystem@2652}
// Banner打印
"springBootBanner" -> {SpringApplicationBannerPrinter$PrintedBanner@2400}
"springBootLoggerGroups" -> {LoggerGroups@2658}
// 系统参数 this.prepareBeanFactory(beanFactory);
"systemProperties" -> {Properties@2749} size = 59
// 环境变量初始化
environment -> {StandardEnvironment@2376}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
singletonObject = {Properties@2749}  size = 59
"java.runtime.name" -> "Java(TM) SE Runtime Environment"
"sun.boot.library.path" -> "D:\Java\jdk1.8\jre\bin"
"java.vm.version" -> "25.152-b16"
"java.vm.vendor" -> "Oracle Corporation"
"java.vendor.url" -> "http://java.oracle.com/"
"path.separator" -> ";"
"java.vm.name" -> "Java HotSpot(TM) 64-Bit Server VM"
"file.encoding.pkg" -> "sun.io"
"user.country" -> "CN"
"user.script" -> ""
"sun.java.launcher" -> "SUN_STANDARD"
"sun.os.patch.level" -> ""
"PID" -> "7840"
"java.vm.specification.name" -> "Java Virtual Machine Specification"
"user.dir" -> "D:\learncode\right-try"
"intellij.debug.agent" -> "true"
"java.runtime.version" -> "1.8.0_152-b16"
"java.awt.graphicsenv" -> "sun.awt.Win32GraphicsEnvironment"
"java.endorsed.dirs" -> "D:\Java\jdk1.8\jre\lib\endorsed"
"os.arch" -> "amd64"
"java.io.tmpdir" -> "C:\Users\LENOVO\AppData\Local\Temp\"
"line.separator" -> "\r\n"
"java.vm.specification.vendor" -> "Oracle Corporation"
"user.variant" -> ""
"os.name" -> "Windows 10"
"sun.jnu.encoding" -> "GBK"
"spring.beaninfo.ignore" -> "true"
"java.library.path" -> "D:\Java\jdk1.8\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;D:\application\VM Ware\bin\;D:\java\jdk1.8\jre\bin;D:\java\jdk1.8\jre;C:\Program Files\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\c++\mingw_7.3.0\bin;D:\java\apache-tomcat-9.0.62\bin;D:\java\apache-tomcat-9.0.62\lib;D:\java\apache-tomcat-9.0.62\bin;D:\java\apache-maven-3.6.3\bin;D:\Python\python-3.10.4;D:\MySQL\mysql-8.0.29-winx64\bin;D:\MySQL\mysql-5.7.20-winx64\bin;D:\java\nacos\bin;D:\application\Git\cmd;C:\ProgramData\chocolatey\bin;D:\Web\nvm;D:\Web\nodejs;D:\Web\nodejs\node-global;D:\java\apache-jmeter-5.5\bin;C:\Program Files\Azure Data Studio\bin;D:\java\Redis-x64-3.0.504;D:\java\Redis-x64-3.0.504;D:\java\mongodb-win32-x86_64-windows-5.0.9\bin;C:\Users\LENOVO\AppData\Local\Microsoft\WindowsApps;D:\java\IntelliJ IDEA 2021.3.3\bin;;D:\application\Microsoft VS Code\bin;D:\java\jdk1.8\jre"
"jboss.modules.system.pkgs" -> "com.intellij.rt"
"java.specification.name" -> "Java Platform API Specification"
"java.class.version" -> "52.0"
"sun.management.compiler" -> "HotSpot 64-Bit Tiered Compilers"
"os.version" -> "10.0"
"user.home" -> "C:\Users\LENOVO"
"user.timezone" -> "Asia/Shanghai"
"java.awt.printerjob" -> "sun.awt.windows.WPrinterJob"
"file.encoding" -> "UTF-8"
"java.specification.version" -> "1.8"
"java.class.path" -> "D:\java\jdk1.8\jre\lib\charsets.jar;D:\java\jdk1.8\jre\lib\deploy.jar;D:\java\jdk1.8\jre\lib\ext\access-bridge-64.jar;D:\java\jdk1.8\jre\lib\ext\cldrdata.jar;D:\java\jdk1.8\jre\lib\ext\dnsns.jar;D:\java\jdk1.8\jre\lib\ext\jaccess.jar;D:\java\jdk1.8\jre\lib\ext\jfxrt.jar;D:\java\jdk1.8\jre\lib\ext\localedata.jar;D:\java\jdk1.8\jre\lib\ext\nashorn.jar;D:\java\jdk1.8\jre\lib\ext\sunec.jar;D:\java\jdk1.8\jre\lib\ext\sunjce_provider.jar;D:\java\jdk1.8\jre\lib\ext\sunmscapi.jar;D:\java\jdk1.8\jre\lib\ext\sunpkcs11.jar;D:\java\jdk1.8\jre\lib\ext\zipfs.jar;D:\java\jdk1.8\jre\lib\javaws.jar;D:\java\jdk1.8\jre\lib\jce.jar;D:\java\jdk1.8\jre\lib\jfr.jar;D:\java\jdk1.8\jre\lib\jfxswt.jar;D:\java\jdk1.8\jre\lib\jsse.jar;D:\java\jdk1.8\jre\lib\management-agent.jar;D:\java\jdk1.8\jre\lib\plugin.jar;D:\java\jdk1.8\jre\lib\resources.jar;D:\java\jdk1.8\jre\lib\rt.jar;D:\learncode\right-try\target\classes;D:\java\apache-maven-3.6.3\repo\org\springframework\boot\spring-boot-starter\2.3.12.RELEASE\spring-b"
"user.name" -> "where"
"java.vm.specification.version" -> "1.8"
"sun.java.command" -> "com.where.right.RightApplication"
"java.home" -> "D:\Java\jdk1.8\jre"
"sun.arch.data.model" -> "64"
"user.language" -> "zh"
"java.specification.vendor" -> "Oracle Corporation"
"awt.toolkit" -> "sun.awt.windows.WToolkit"
"java.vm.info" -> "mixed mode"
"java.version" -> "1.8.0_152"
"java.ext.dirs" -> "D:\Java\jdk1.8\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext"
"sun.boot.class.path" -> "D:\Java\jdk1.8\jre\lib\resources.jar;D:\Java\jdk1.8\jre\lib\rt.jar;D:\Java\jdk1.8\jre\lib\sunrsasign.jar;D:\Java\jdk1.8\jre\lib\jsse.jar;D:\Java\jdk1.8\jre\lib\jce.jar;D:\Java\jdk1.8\jre\lib\charsets.jar;D:\Java\jdk1.8\jre\lib\jfr.jar;D:\Java\jdk1.8\jre\classes;C:\Users\LENOVO\AppData\Local\JetBrains\IntelliJIdea2021.3\captureAgent\debugger-agent.jar"
"java.awt.headless" -> "true"
"java.vendor" -> "Oracle Corporation"
"file.separator" -> "\"
"java.vendor.url.bug" -> "http://bugreport.sun.com/bugreport/"
"sun.io.unicode.encoding" -> "UnicodeLittle"
"sun.cpu.endian" -> "little"
"sun.desktop" -> "windows"
"sun.cpu.isalist" -> "amd64"
1
environment -> {StandardEnvironment@2376} "StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[ConfigurationPropertySourcesPropertySource {name='configurationProperties'}, PropertiesPropertySource {name='systemProperties'}, OriginAwareSystemEnvironmentPropertySource {name='systemEnvironment'}, RandomValuePropertySource {name='random'}]}2"

spring-boot-autoconfiguration模块

AutoConfigurationImportSelector

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
private static final AutoConfigurationImportSelector.AutoConfigurationEntry EMPTY_ENTRY = new AutoConfigurationImportSelector.AutoConfigurationEntry();
private static final String[] NO_IMPORTS = new String[0];
private static final Log logger = LogFactory.getLog(AutoConfigurationImportSelector.class);
private static final String PROPERTY_NAME_AUTOCONFIGURE_EXCLUDE = "spring.autoconfigure.exclude";
private ConfigurableListableBeanFactory beanFactory;
private Environment environment;
private ClassLoader beanClassLoader;
private ResourceLoader resourceLoader;
private AutoConfigurationImportSelector.ConfigurationClassFilter configurationClassFilter;

// 自动注入的配置信息 实体
protected static class AutoConfigurationEntry {
// 全路径名
private final List<String> configurations;
// 需要排除的 类
private final Set<String> exclusions;
}

// 通过 @EnableAutoConfiguration

public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
// 封装为 实体信息 = 注入配置类 + 排除配置类
AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}

protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
} else {
AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
// 获取 configurations的全路径名
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
configurations = this.removeDuplicates(configurations);
// 通过注解获取需要排除的 类信息
Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
this.checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = this.getConfigurationClassFilter().filter(configurations);
this.fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
}
}
// 获取需要进行自动注入的候选对象的 全路径名 数组
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
// 通过 @EnableAutoConfiguration注解的Class,获取spring.factory中以 其为key的value数组
// 数组为,需要进行自动注入的对象信息
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
return configurations;
}

protected Class<?> getSpringFactoriesLoaderFactoryClass() {
return EnableAutoConfiguration.class;
}
}

image-20230407235054392

Condition

了解 Spring Boot AutoConfiguration - 知乎 (zhihu.com)

SpringFrameWork

(3条消息) Spring模块组成(框架组成、整体架构、体系架构、体系结构)_spring由那些模块组成_ThinkWon的博客-CSDN博客

在这里插入图片描述

七大模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1. Spring Core
框架的最基础部分,提供 IoC 容器,对 bean 进行管理。

2.Spring Context
基于 bean,提供上下文信息,扩展出JNDI、EJB、电子邮件、国际化、校验和调度等功能。

3.Spring DAO
提供了JDBC的抽象层,它可消除冗长的JDBC编码和解析数据库厂商特有的错误代码,还提供了声明性事务管理方法。

4.Spring ORM
提供了常用的“对象/关系”映射APIs的集成层。 其中包括JPA、JDO、Hibernate、MyBatis 等。

5.Spring AOP
提供了符合AOP Alliance规范的面向方面的编程实现。

6.Spring Web
提供了基础的 Web 开发的上下文信息,可与其他 web 进行集成。

7.Spring Web MVC
提供了 Web 应用的 Model-View-Controller 全功能实现。

核心容器

Spring的核心容器是其他模块建立的基础,有spring-core、spring-beans、spring-context、spring-context-support和spring-expression(Spring表达式语言)等模块组成。

1
2
3
4
5
6
7
8
9
spring-core 模块:提供了框架的基本组成部分,包括控制反转(Inversion of Control,IOC)和依赖注入(Dependency Injection,DI)功能。

spring-beans 模块:提供了BeanFactory,是工厂模式的一个经典实现,Spring将管理对象称为Bean。

spring-context 模块:建立在Core和Beans模块的基础之上,提供一个框架式的对象访问方式,是访问定义和配置的任何对象的媒介。ApplicationContext接口是Context模块的焦点。

spring-context-support 模块:支持整合第三方库到Spring应用程序上下文,特别是用于高速缓存(EhCache、JCache)和任务调度(CommonJ、Quartz)的支持。

Spring-expression 模块:提供了强大的表达式语言去支持运行时查询和操作对象图。这是对JSP2.1规范中规定的统一表达式语言(Unified EL)的扩展。该语言支持设置和获取属性值、属性分配、方法调用、访问数组、集合和索引器的内容、逻辑和算术运算、变量命名以及从Spring的IOC容器中以名称检索对象。它还支持列表投影、选择以及常用的列表聚合。

AOP 和设备支持

由spring-aop、 spring-aspects 和 spring-instrument等 3 个模块组成。

1
2
3
4
5
spring-aop 模块:是 Spring 的另一个核心模块,提供了一个符合 AOP 要求的面向切面的编程实现。 作为继 OOP(面向对象编程) 后, 对程序员影响最大的编程思想之一, AOP 极大地开拓了人们对于编程的思路。 在 Spring 中, 以动态代理技术为基础,允许定义方法拦截器和切入点,将代码按照功能进行分离,以便干净地解耦。

spring-aspects 模块:提供了与AspectJ的集成功能,AspectJ是一个功能强大且成熟的AOP框架。

spring-instrument 模块:是 AOP 的一个支援模块, 提供了类植入(Instrumentation)支持和类加载器的实现,可以在特定的应用服务器中使用。主要作用是在 JVM 启用时, 生成一个代理类, 程序员通过代理类在运行时修改类的字节, 从而改变一个类的功能, 实现 AOP 的功能。

数据访问与集成

spring-jdbc、spring-orm、spring-oxm、spring-jms 和 spring-tx 等 5 个模块组成。

1
2
3
4
5
6
7
8
9
spring-jdbc 模块:提供了一个JDBC的抽象层,消除了烦琐的JDBC编码和数据库厂商特有的错误代码解析, 用于简化JDBC。主要是提供 JDBC 模板方式、 关系数据库对象化方式、 SimpleJdbc 方式、 事务管理来简化 JDBC 编程, 主要实现类是 JdbcTemplate、 SimpleJdbcTemplate 以及 NamedParameterJdbcTemplate。

spring-orm 模块:是 ORM 框架支持模块, 主要集成 Hibernate, Java Persistence API (JPA) 和Java Data Objects (JDO) 用于资源管理、 数据访问对象(DAO)的实现和事务策略。

spring-oxm 模块:主要提供一个抽象层以支撑 OXM(OXM 是 Object-to-XML-Mapping 的缩写, 它是一个 O/M-mapper, 将 java 对象映射成 XML 数据, 或者将 XML 数据映射成 java 对象) , 例如: JAXB,Castor,XMLBeans,JiBX 和 XStream 等。

spring-jms模块(Java Messaging Service):指Java消息传递服务,包含用于生产和使用消息的功能。自Spring4.1以后,提供了与spring-messaging模块的集成。

spring-tx 模块:事务模块,支持用于实现特殊接口和所有POJO(普通Java对象)类的编程和声明式事务管理。

Web

spring-websocket、spring-webmvc、spring-web、portletspring-webflux模块等 5 个模块组成。

1
2
3
4
5
6
7
8
9
spring-websocket 模块:Spring4.0以后新增的模块,实现双工异步通讯协议,实现了WebSocket和SocketJS,提供Socket通信和web端的推送功能。

spring-webmvc 模块:也称为Web-Servlet模块,包含用于web应用程序的Spring MVC和REST Web Services实现。Spring MVC框架提供了领域模型代码和Web表单之间的清晰分离,并与Spring Framework的所有其他功能集成。

spring-web 模块:提供了基本的Web开发集成功能,包括使用Servlet监听器初始化一个IOC容器以及Web应用上下文,自动载入WebApplicationContext特性的类,Struts集成类、文件上传的支持类、Filter类和大量辅助工具类。

portlet 模块:实现web模块功能的聚合,类似于Servlet模块的功能,提供了Portlet环境下的MVC实现。

spring-webflux 模块:是一个新的非堵塞函数式 Reactive Web 框架, 可以用来建立异步的, 非阻塞,事件驱动的服务, 并且扩展性非常好。

消息(Messaging)

即 spring-messaging 模块。

1
spring-messaging 是从 Spring4 开始新加入的一个模块, 该模块提供了对消息传递体系结构和协议的支持。

Test

即 spring-test 模块。

1
spring-test 模块主要为测试提供支持的,支持使用JUnit或TestNG对Spring组件进行单元测试和集成测试。

Maven依赖

所有模块的依赖引入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<properties>
<org.springframework.version>5.0.8.RELEASE</org.springframework.version>
</properties>
<dependencies>
<!-- spring start -->

<!--spring core start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-indexer</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring core end-->

<!--spring aop start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spirng aop end-->

<!--spring aspects start-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring aspects end-->

<!--spring instrumentation start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-instrument</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring instrumentation end-->

<!--spring messaging start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring messaging end-->

<!--spring data access start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring data access end-->

<!--spring web start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring web end -->

<!--spring test start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!--spring test end -->
<!-- spring end -->
</dependencies>


packaget-info.java

1
2
3
4
5
1、为标注在包上Annotation提供便利;

2、声明友好类和包常量;

3、提供包的整体注释说明。
1
2
3
4
5
6
7
8
9
10
11
/**
* Classes supporting the org.springframework.context package,
* such as abstract base classes for ApplicationContext
* implementations and a MessageSource implementation.
*/
@NonNullApi 用于声明参数和返回值在默认情况下对于给定的包被视为不可为空。
@NonNullFields 用于声明对于给定的包,默认情况下字段将被视为不可为空
package org.springframework.context.support;

import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;

工具类

AnnotationConfigUtils

AnnotationBeanDefinitionReader调用用于注册PostProcessor

PostProcessorRegistrationDelegate

执行refresh()的 invokePostProcessor() 和 registerPostProcessor()方法

ResolvableType

不知道

BeanUtils

SpringFactoriesLoader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public final class SpringFactoriesLoader {
// 路径
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class);
private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap();

// 通过 @EnableAutoConfiguration注解的Class,获取spring.factory中以 其为key的value数组
// 数组为,需要进行自动注入的对象信息
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
return configurations;
}
protected Class<?> getSpringFactoriesLoaderFactoryClass() {
return EnableAutoConfiguration.class;
}


public static <T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) {
Assert.notNull(factoryType, "'factoryType' must not be null");
ClassLoader classLoaderToUse = classLoader;
if (classLoader == null) {
classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
}
// 获取对应key的 values
List<String> factoryImplementationNames = loadFactoryNames(factoryType, classLoaderToUse);
if (logger.isTraceEnabled()) {
logger.trace("Loaded [" + factoryType.getName() + "] names: " + factoryImplementationNames);
}

List<T> result = new ArrayList(factoryImplementationNames.size());
Iterator var5 = factoryImplementationNames.iterator();

while(var5.hasNext()) {
String factoryImplementationName = (String)var5.next();
// 实例化 并 加入到 result
result.add(instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse));
}

AnnotationAwareOrderComparator.sort(result);
return result;
}
// 获取对应key的 values
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
String factoryTypeName = factoryType.getName();
return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
}

———-《再看Spring》———–

Spring Boot

Spring Boot run方法执行流程_springboot run方法的主要流程-CSDN博客

main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.sources = new LinkedHashSet();
this.bannerMode = Mode.CONSOLE;
this.logStartupInfo = true;
this.addCommandLineProperties = true;
this.addConversionService = true;
this.headless = true;
this.registerShutdownHook = true;
this.additionalProfiles = new HashSet();
this.isCustomEnvironment = false;
this.lazyInitialization = false;
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
//把SpringdemoApplication.class设置为属性存储起来
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
//设置应用类型为Standard还是Web
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//设置初始化器(Initializer),最后会调用这些初始化器
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
//设置监听器(Listener)
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = this.deduceMainApplicationClass();
}

Run

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*从run方法进来*/
public ConfigurableApplicationContext run(String... args) {
//计时工具
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
this.configureHeadlessProperty();
//第一步,获取并启动监听器
SpringApplicationRunListeners listeners = this.getRunListeners(args);
listeners.starting();

Collection exceptionReporters;
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//第二步,根据SpringApplicationRunListeners以及参数来准备环境
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
//准备Banner打印器‐就是启动Spring Boot的时候在console上的ASCII艺术字体
Banner printedBanner = this.printBanner(environment);
//第三步:创建Spring容器
context = this.createApplicationContext();
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
//第四步:Spring容器前置处理
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//第五步:刷新容器
this.refreshContext(context);
//第六步:Spring容器后置处理
this.afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
//第七步:发出结束执行的事件
listeners.started(context);
//第八步:执行Runners
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
}

try {
listeners.running(context);
//返回容器
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}

img

Refresh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

// 一、Prepare this context for refreshing.
prepareRefresh();

// 二、Tell the subclass to refresh the internal bean factory.
// 二、通知子类 初始化(refresh) - 子类对BeanFactory的增强逻辑 BeanFactory同时,获取BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// 三、Prepare the bean factory for use in this context.
// 一些Context 上下文的配置
prepareBeanFactory(beanFactory);

try {
// 四、Allows post-processing of the bean factory in context subclasses.
// 四、子类对 BeanFactory 进行增强
postProcessBeanFactory(beanFactory);

StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// 五、Invoke factory processors registered as beans in the context.
// 五、执行已经注册为 BeanDefinition 的 BeanFactoryPostProcessors
invokeBeanFactoryPostProcessors(beanFactory);

// 六、Register bean processors that intercept bean creation.
// 六、注册、初始化 已经注册为BeanDefinition 的 BeeanPostProcesscor
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();

// 七、Initialize message source for this context.
initMessageSource();

// 八、Initialize event multicaster for this context.
// 八、初始化事件广播器
initApplicationEventMulticaster();

// 九、Initialize other special beans in specific context subclasses.
// 九、子类初始化 其他特殊 Bean
onRefresh();

// 十、Check for listener beans and register them.
// 十、注册 Listener 实例 和 ListenerName 到 multicastr
registerListeners();

// 十一、Instantiate all remaining (non-lazy-init) singletons.
// 十一、初始化 非懒加载的 单例bean
finishBeanFactoryInitialization(beanFactory);

// 十二、Last step: publish corresponding event.
// 十二、发布 finish 事件
finishRefresh();
}

catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}

// Destroy already created singletons to avoid dangling resources.
// 销毁已经创建的Bean
destroyBeans();

// Reset 'active' flag.
//
cancelRefresh(ex);

// Propagate exception to caller.
throw ex;
}

finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
contextRefresh.end();
}
}
}

重要的 PostProccesor

重要的 Context

  • AbstractApplicationContext ## refrsh

注解相关的 Context - 自动注入

AnnotationConfigApplicationContext

两个 Reader、Scanner 用于 BeanDefinition的注册扫描

在 上下文初始化的手创建和初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
// register - 注解扫描
private final AnnotatedBeanDefinitionReader reader;

/*
@Configuration 、 @Conponent
*/
// scan - 包扫描
private final ClassPathBeanDefinitionScanner scanner;

/*
@ConfigurationScan
*/
public AnnotationConfigApplicationContext() {
StartupStep createAnnotatedBeanDefReader = getApplicationStartup().start("spring.context.annotated-bean-reader.create");
// 这个方法很重要 --- 这里是一些注解处理的 PostPrcessor 注册的地方
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
}

AnnotatedBeanDefinitionReader的初始化(非常重要-@Autowired)

1
2
3
4
5
6
7
8
9
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
//
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}

AnnotationConfigUtils

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {
// 用 register 包装创建 DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}
// 注册一些重要的 BeanDefinition(PostProcessor),
// ---- 在后面实例化的(PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors())
// ----- (PostProcessorRegistrationDelegate.registerBeanPostProcessors())
Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
// ConfigurationClassPostProcessor, 究极重要--配置类@Configuraion 解析
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}

if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
// AutowiredAnnotationBeanPostProcessor -- @Autowired 注解解析 --自动注入
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}

// Check for Jakarta Annotations support, and if present add the CommonAnnotationBeanPostProcessor.
if ((jakartaAnnotationsPresent || jsr250Present) &&
!registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
//
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}

// JPA 相关的支持
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}

// EventListenerMethodProcessor -- @EventListener 注解的支持
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}

// EventListenerMethodProcessor -- @EventListener 注解的支持
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}

return beanDefs;
}

重要的工具类

主要用于重要方法的执行,重要类的 BeanDefinition 的注册,BeanDefinition的实例化

AnnotationConfigUtils

Spring 注解、JPA 注解(Java 注解规范)

@Configuration @Autowired @EnventListerner @Inject

注册相关的 支持类为 BeanDefinition,后面 在 PostProcessorRegistrationDelegate 的时候注册为 Bean,实现相关功能

registerAnnotationConfigProcessors –

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
 * @see ContextAnnotationAutowireCandidateResolver
* @see ConfigurationClassPostProcessor
* @see CommonAnnotationBeanPostProcessor
* @see org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
* @see org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor
*/
public abstract class AnnotationConfigUtils {

/**
* The bean name of the internally managed Configuration annotation processor.
*/
public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalConfigurationAnnotationProcessor";

/**
* The bean name of the internally managed BeanNameGenerator for use when processing
* {@link Configuration} classes. Set by {@link AnnotationConfigApplicationContext}
* and {@code AnnotationConfigWebApplicationContext} during bootstrap in order to make
* any custom name generation strategy available to the underlying
* {@link ConfigurationClassPostProcessor}.
* @since 3.1.1
*/
public static final String CONFIGURATION_BEAN_NAME_GENERATOR =
"org.springframework.context.annotation.internalConfigurationBeanNameGenerator";

/**
* The bean name of the internally managed Autowired annotation processor.
*/
public static final String AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalAutowiredAnnotationProcessor";

/**
* The bean name of the internally managed common annotation processor.
*/
public static final String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalCommonAnnotationProcessor";

/**
* The bean name of the internally managed JPA annotation processor.
*/
public static final String PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalPersistenceAnnotationProcessor";

private static final String PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME =
"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor";

/**
* The bean name of the internally managed @EventListener annotation processor.
*/
public static final String EVENT_LISTENER_PROCESSOR_BEAN_NAME =
"org.springframework.context.event.internalEventListenerProcessor";

/**
* The bean name of the internally managed EventListenerFactory.
*/
public static final String EVENT_LISTENER_FACTORY_BEAN_NAME =
"org.springframework.context.event.internalEventListenerFactory";


private static final ClassLoader classLoader = AnnotationConfigUtils.class.getClassLoader();

private static final boolean jakartaAnnotationsPresent =
ClassUtils.isPresent("jakarta.annotation.PostConstruct", classLoader);

private static final boolean jsr250Present =
ClassUtils.isPresent("javax.annotation.PostConstruct", classLoader);

private static final boolean jpaPresent =
ClassUtils.isPresent("jakarta.persistence.EntityManagerFactory", classLoader) &&
ClassUtils.isPresent(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, classLoader);
}

PostProcessorRegistrationDelegate

一些重要方法的执行

  • invokeBeanFactoryPostProcessors — refresh() 方法调用,执行 BeanFactoryPostPRcessor

  • registerBeanPostProcessors. – refresh() 方法调用 注册 BeanPostProcessor

loadBeanPostProcessors – 加载 和 排序 BeanPostProcessor

invokeMergedBeanDefinitionPostProcessors — 执行 MergedBeanDefinitionPostProcessors

sortPostProcessors – 按照Order、PrioryOrder 排序

invokeBeanDefinitionRegistryPostProcessors – 执行 BeanDefinitionRegistryPostProcessors

1
2
3
4
final class PostProcessorRegistrationDelegate {


}

自动注入相关

AutowireCapableBeanFactory

用于自动注入的工厂

AutowiredAnnotationBeanPostProcessor - 框架

实现了

InstantiationAwareBeanPostProcessor 的 postProcessProperties 方法,

InstantiationAwareBeanPostProcessor 明细

三个方法,主要是实例化(反射实例化)的前后步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

// Initialization - 2 = 初始化- 2
// Instantiation - 1 = 实例化- 1
// 1
// 1
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
// 2
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}
// 3
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {

return pvs;
}

AutowiredAnnotationBeanPostProcessor 步骤

postProcessProperties() -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
// 找到需要注入的位置 InjectionMetadata (注入点-属性、方法)
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
// 属性注入
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}

支持三种注入的自动注入(这个类实现的支持)

Autowired、Value、Inject

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public AutowiredAnnotationBeanPostProcessor() {
// Autowired
this.autowiredAnnotationTypes.add(Autowired.class);
// Value
this.autowiredAnnotationTypes.add(Value.class);

try {
// Inject
// jakarta.inject.Inject
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("jakarta.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
logger.trace("'jakarta.inject.Inject' annotation found and supported for autowiring");
}
catch (ClassNotFoundException ex) {
// jakarta.inject API not available - simply skip.
}

try {
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
logger.trace("'javax.inject.Inject' annotation found and supported for autowiring");
}
catch (ClassNotFoundException ex) {
// javax.inject API not available - simply skip.
}
}

Bean 生命周期

  • finishBeanFactoryInitialization()

  • preInstantiateSingletons()

  • getBean()

  • doGetBean()

  • createBean()

  • doCreateBean()

  • populationBean()

  • initializeBean()

Spring Bean 生命周期

Spring Bean 生命周期

< InstantiationAwareBeanPostProcessor >

实例化前 -

  • postProcessorBeforeInstantation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {

/**
* Apply this BeanPostProcessor <i>before the target bean gets instantiated</i>.
* The returned bean object may be a proxy to use instead of the target bean,
* effectively suppressing default instantiation of the target bean.
* <p>If a non-null object is returned by this method, the bean creation process
* will be short-circuited. The only further processing applied is the
* {@link #postProcessAfterInitialization} callback from the configured
* {@link BeanPostProcessor BeanPostProcessors}.
* <p>This callback will be applied to bean definitions with their bean class,
* as well as to factory-method definitions in which case the returned bean type
* will be passed in here.
* <p>Post-processors may implement the extended
* {@link SmartInstantiationAwareBeanPostProcessor} interface in order
* to predict the type of the bean object that they are going to return here.
* <p>The default implementation returns {@code null}.
* @param beanClass the class of the bean to be instantiated
* @param beanName the name of the bean
* @return the bean object to expose instead of a default instance of the target bean,
* or {@code null} to proceed with default instantiation
* @throws org.springframework.beans.BeansException in case of errors
* @see #postProcessAfterInstantiation
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#getBeanClass()
* @see org.springframework.beans.factory.support.AbstractBeanDefinition#getFactoryMethodName()
*/
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
return null;
}

/**
* Perform operations after the bean has been instantiated, via a constructor or factory method,
* but before Spring property population (from explicit properties or autowiring) occurs.
* <p>This is the ideal callback for performing custom field injection on the given bean
* instance, right before Spring's autowiring kicks in.
* <p>The default implementation returns {@code true}.
* @param bean the bean instance created, with properties not having been set yet
* @param beanName the name of the bean
* @return {@code true} if properties should be set on the bean; {@code false}
* if property population should be skipped. Normal implementations should return {@code true}.
* Returning {@code false} will also prevent any subsequent InstantiationAwareBeanPostProcessor
* instances being invoked on this bean instance.
* @throws org.springframework.beans.BeansException in case of errors
* @see #postProcessBeforeInstantiation
*/
default boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
return true;
}

/**
* Post-process the given property values before the factory applies them
* to the given bean.
* <p>The default implementation returns the given {@code pvs} as-is.
* @param pvs the property values that the factory is about to apply (never {@code null})
* @param bean the bean instance created, but whose properties have not yet been set
* @param beanName the name of the bean
* @return the actual property values to apply to the given bean (can be the passed-in
* PropertyValues instance), or {@code null} to skip property population
* @throws org.springframework.beans.BeansException in case of errors
* @since 5.1
*/
// 属性注入增强
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName)
throws BeansException {

return pvs;
}

}

实例化 - doCreateBean

  • doCreateBean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

// Instantiate the bean.
// 创建Bean 实例 -- class
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 创建Bean 实例 -- class
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}

// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// MergedBeanDefinitionPostProcessor ## postProcessMergedBeanDefinition
// 修改 特殊的 Bean的 BeanDefinition
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.markAsPostProcessed();
}
}

// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// 解决循环依赖问题:二级缓存 -- 实例
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 添加了 ObjectFactory
// 调用了 实例化时 的 BeanPostProcessor
// getEarlyBeanReference -》 SmartInstantiationAwareBeanPostProcessor ## getEarlyBeanReference
// 如果发生循环依赖,就在这里获取提前 aop 代理对象 (这是一个工厂方法,交给后面的实例化前方法调用)
// postProcessBeforeInitialization
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

// Initialize the bean instance.
Object exposedObject = bean;
try {
// 属性填充
populateBean(beanName, mbd, instanceWrapper);
// 实例化
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException bce && beanName.equals(bce.getBeanName())) {
throw bce;
}
else {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, ex.getMessage(), ex);
}
}

// 关闭三级缓存,并更改当前对象为 代理对象
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}

// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}

return exposedObject;
}

实例化后

  • postProcessorAfterInstantation

属性填充 - populateBean

  • populateBean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}

if (bw.getWrappedClass().isRecord()) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to a record");
}
else {
// Skip property population phase for records since they are immutable.
return;
}
}

// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// 实例化后 的 增强方法
// InstantiationAwareBeanPostProcessor ## postProcessAfterInstantiation
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}

PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

// 按照 BeanName 和 BeanType ,获取 bean
// 然后填充到 PropertyValues pvs
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}

// 注解
// 自动注入:AutowiredAnnotationBeanPostProcessor ## postProcessProperties()
if (hasInstantiationAwareBeanPostProcessors()) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
// 实例化后的 属性PropertyValues 增强方法
// InstantiationAwareBeanPostProcessor ## postProcessProperties
// 自动注入的入口 AutowiredAnnotationBeanPostProcessor ## postProcessProperties
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
pvs = pvsToUse;
}
}

boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
if (needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
checkDependencies(beanName, mbd, filteredPds, pvs);
}

// 将属性值 pvs 统一应用到 bean对象上
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}

< BeanPostProcessor >

初始化前 -

  • postProcessorBeforeInitialization
1
2
3
4
5
6
7
8
9
10
11
12
public interface BeanPostProcessor {
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}

@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}

}

Aware 接口 具体实现

  • ApplicationContextAwareProcessor ## postProcessBeforeInitialization

Aware Processor会在Bean的实例化之后,初始化之前执行。

1
2
3
4
5
6
7
8
9
Spring框架中有以下几种Aware Processor:

BeanFactoryAwareProcessor:用于处理实现了BeanFactoryAware接口的Bean,该接口提供了对BeanFactory的访问。
ApplicationContextAwareProcessor:用于处理实现了ApplicationContextAware接口的Bean,该接口提供了对ApplicationContext的访问。
MessageSourceAwareProcessor:用于处理实现了MessageSourceAware接口的Bean,该接口提供了对MessageSource的访问,用于国际化消息的处理。
ApplicationEventPublisherAwareProcessor:用于处理实现了ApplicationEventPublisherAware接口的Bean,该接口提供了对ApplicationEventPublisher的访问,用于发布和监听应用程序事件。
ResourceLoaderAwareProcessor:用于处理实现了ResourceLoaderAware接口的Bean,该接口提供了对ResourceLoader的访问,用于加载资源文件。
EnvironmentAwareProcessor:用于处理实现了EnvironmentAware接口的Bean,该接口提供了对Environment的访问,用于获取应用程序的环境变量和属性。
这些Aware Processor可以在Bean实例化过程中自动调用,将相应的资源或对象注入到实现了相应Aware接口的Bean中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

class ApplicationContextAwareProcessor implements BeanPostProcessor {
// 初始化之前,填充bean 的 aware属性
@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 ||
bean instanceof ApplicationStartupAware)) {
return bean;
}

invokeAwareInterfaces(bean);
return bean;
}
// 具体实现
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware environmentAware) {
environmentAware.setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware embeddedValueResolverAware) {
embeddedValueResolverAware.setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware resourceLoaderAware) {
resourceLoaderAware.setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware applicationEventPublisherAware) {
applicationEventPublisherAware.setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware messageSourceAware) {
messageSourceAware.setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationStartupAware applicationStartupAware) {
applicationStartupAware.setApplicationStartup(this.applicationContext.getApplicationStartup());
}
if (bean instanceof ApplicationContextAware applicationContextAware) {
applicationContextAware.setApplicationContext(this.applicationContext);
}
}
}
}

初始化 - initializeBean

  • init-method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
invokeAwareMethods(beanName, bean);

Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 初始化之前的增强器 Bean
// BeanPostProcessor ## postProcessBeforeInitialization
// 调用 getEarlyBeanReference 进行提前到aop代理(如果发生循环依赖)
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

try {
// 执行初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null), beanName, ex.getMessage(), ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 初始化之后的增强器 --- AbstractAutoProxyCreator ## postProcessAfterInitialization()
// 没有循环依赖的 aop代理生成
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}

return wrappedBean;
}

初始化后

  • postProcessorAfterInitialization

AOP 代理

正常AOP流程

img

循环依赖下的AOP 提前代理

创建 B 的时候,需要从三级缓存获取 A。

此时在 getSingleton 方法中会调用:singletonObject = singletonFactory.getObject();

img

B 属性赋值时,从三级缓存获取 A

有时会比较疑惑 singletonFactory.getObject() 调用的是哪里?

img

三级缓存获取对象

所以这一块调用的是 getEarlyBeanReference,开始遍历执行 BeanPostProcessor

img

getEarlyBeanReference

img

getEarlyBeanReference

看到 wrapIfNecessary 就明白了吧!这块会获取一个代理对象

也就是说此时返回,并放到二级缓存的是一个 A 的代理对象。

这样 B 就创建完毕了!

到 A 开始初始化并执行后置处理器了!因为 A 也有代理,所以 A 也会执行到 postProcessAfterInitialization 这一部分!

img

判断二级缓存

但是在执行 wrapIfNecessary 之前,会先判断代理对象的标记缓存是否有 A 了。

1
this.earlyProxyReferences.remove(cacheKey) != bean

但是这块获取到的是 A 的代理对象。肯定是 false 。所以不会再生成一次 A 的代理对象

img

———-《三级缓存》———–

循序渐进,看一看什么是循环依赖?

场景

A引用B ,B引用A。

Spring如何帮我们创建A和B对象

三级缓存是什么

  • singletonObjects, 一级缓存
  • earlySingletonObjects, 二级缓存
  • singletonFactories 三级缓存

缓存其实就是三个Map

img

对象创建步骤白话版

  1. 对象A要创建到Spring容器中,从一级缓存singletonObject获取A,不存在,开始实例化A,最终在三级缓存singletonObjectFactory添加(A,A的函数式接口创建方法),这时候A有了自己的内存地址
  2. 设置属性B,B也从一级缓存singletonObject获取B,不存在,开始实例化B,最终在三级缓存singletonObjectFactory添加(B,B的函数式接口创建方法),这时候B有了自己的内存地址
  3. B中开始给属性A赋值,此时会找到三级缓存中的A,并将A放入二级缓存中。删除三级缓存
  4. B初始化完成,从三级缓存singletonObjectFactory直接put到一级缓存singletonObject,并删除二级和三级缓存的自己
  5. A成功得到B,A完成初始化动作,从二级缓存中移入一级缓存,并删除二级和三级缓存的自己
  6. 最终A和B都进入一级缓存中待用户使用

singletonObjects: 一级缓存,存储单例对象,Bean 已经实例化,初始化完成。 earlySingletonObjects: 二级缓存,存储 singletonObject,这个 Bean 实例化了,还没有初始化。 singletonFactories: 三级缓存,存储 singletonFactory。

1、Bean 的创建过程

@Service public class CircularServiceA { private String fieldA = “字段 A”; }
复制

img

单例 Bean 的创建过程

通过上面的流程,可以看出 Spring 在创建 Bean 的过程中重点是在 AbstractAutowireCapableBeanFactory 中的以下三个步骤:

  1. 实例化 createBeanInstance: 其中实例化 Bean 并对 Bean 进行赋值,像例子中的 fieldA 字段在这里就会赋值。
  2. 属性注入 populateBean: 可以理解为对 Bean 里面的属性进行赋值。(会依赖其他 Bean)
  3. 初始化 initializeBean: 执行初始化和 Bean 的后置处理器。

实例化赋值源码可以阅读: BeanUtils.instantiateClass(constructorToUse)

如果要依赖其他 Bean 呢?

那如果 CircularServiceA 依赖了其他 Bean 呢?

@Service public class CircularServiceA { private String fieldA = “字段 A”; @Autowired private CircularServiceB circularServiceB; } @Service public class CircularServiceB { }
复制

img

A 依赖了 B

当 A 依赖了 B 的时候,在 createBeanInstance 这一步,并不会对 B 进行属性赋值。

而是在 populatedBean 这里查找依赖项,并创建 B。

2、循环依赖下的创建过程

循环依赖的场景,在上一篇文章已经有所讲解,这里仅仅画图说明一下。

@Service public class CircularServiceA { private String fieldA = “字段 A”; @Autowired private CircularServiceB circularServiceB; } @Service public class CircularServiceB { @Autowired private CircularServiceA circularServiceA; }
复制

img

A B 循环依赖

在 A 和 B 循环依赖的场景中:

B populatedBean 查找依赖项 A 的时候,从一级缓存中虽然未获取到 A,但是发现 A 在创建中。

此时,从三级缓存中获取 A 的 singletonFactory 调用工厂方法,创建 getEarlyBeanReference A 的早期引用并返回。

B 引用到 A ,B 就可以初始化完毕,然后 A 同样也可以初始化完毕了。

二级缓存能否解决循环依赖

通过上面的图,仔细分析一下,其实把二级缓存拿掉,在 B 尝试获取 A 的时候直接返回 A 的实例,是不是也是可以的?

答案是:可以的!

但是为什么还是用三级缓存呢?

网上的很多资料说是和动态代理有关系,那就从动态代理的方面继续往下分析分析。

动态代理的场景

在 JavaConfig(配置类) 上添加 @EnableAspectJAutoProxy 注解,开启 AOP ,通过 Debug 循序渐进看一看动态代理对循环依赖的影响。

3、动态代理下,Bean 的创建过程

@Service public class CircularServiceA { private String fieldA = “字段 A”; public void methodA() { System.out.println(“方法 A 执行”); } } @Aspect @Component public class AspectA { @Before(“execution(public void com.liuzhihang.circular.CircularServiceA.methodA())”) public void beforeA() { System.out.println(“beforeA 执行”); } }
复制

只有 A 的情况下,给 A 添加切面,开始 Debug。

前面的流程都相同,在 initializeBean 开始出现差异。

这一步需要初始化 Bean 并执行 Bean 的后置处理器。

img

执行后置处理器

其中有一个处理器为:AnnotationAwareAspectJAutoProxyCreator 其实就是加的注解切面,会跳转到 AbstractAutoProxyCreator 类的 postProcessAfterInitialization 方法

img

postProcessAfterInitialization

如图所示:wrapIfNecessary 方法会判断是否满足代理条件,是的话返回一个代理对象,否则返回当前 Bean。

后续调用 getProxy 、createAopProxy 等等,最终执行到下面一部分。

img

最终会执行到这里,AOP 代理相关的就不细看了。

一路放行,直到 initializeBean 执行结束。

img

A 被替换为了代理对象

此时发现:A 被替换为了代理对象。

所以 doCreateBean 返回,以及后面放到一级缓存中的都是代理对象。

img

红框部分为差异

4、有循环依赖的动态代理

这一次把循环依赖打开:

@Service public class CircularServiceA { private String fieldA = “字段 A”; @Autowired private CircularServiceB circularServiceB; public void methodA() { System.out.println(“方法 A 执行”); } } @Aspect @Component public class AspectA { @Before(“execution(public void com.liuzhihang.circular.CircularServiceA.methodA())”) public void beforeA() { System.out.println(“beforeA 执行”); } } @Service public class CircularServiceB { @Autowired private CircularServiceA circularServiceA; public void methodB() { } } @Aspect @Component public class AspectB { @Before(“execution(public void com.liuzhihang.circular.CircularServiceB.methodB())”) public void beforeB() { System.out.println(“beforeB 执行”); } }
复制

开始 Debug,前面的一些列流程,都和正常的没有什么区别。而唯一的区别在于,创建 B 的时候,需要从三级缓存获取 A。

此时在 getSingleton 方法中会调用:singletonObject = singletonFactory.getObject();

img

B 属性赋值时,从三级缓存获取 A

有时会比较疑惑 singletonFactory.getObject() 调用的是哪里?

img

三级缓存获取对象

所以这一块调用的是 getEarlyBeanReference,开始遍历执行 BeanPostProcessor

img

getEarlyBeanReference

img

getEarlyBeanReference

看到 wrapIfNecessary 就明白了吧!这块会获取一个代理对象

也就是说此时返回,并放到二级缓存的是一个 A 的代理对象。

这样 B 就创建完毕了!

到 A 开始初始化并执行后置处理器了!因为 A 也有代理,所以 A 也会执行到 postProcessAfterInitialization 这一部分!

img

判断二级缓存

但是在执行 wrapIfNecessary 之前,会先判断代理对象的标记缓存是否有 A 了。

1
this.earlyProxyReferences.remove(cacheKey) != bean

但是这块获取到的是 A 的代理对象。肯定是 false 。所以不会再生成一次 A 的代理对象。

img

代理 - 循环依赖

总结

可以看到,循环依赖下,有没有代理情况下的区别就在:

1
singletonObject = singletonFactory.getObject();

在循环依赖发生的情况下 B 中的 A 赋值时:

  1. 无代理:getObject 直接返回原来的 Bean
  2. 有代理:getObject 返回的是代理对象

然后都放到二级缓存

为什么要三级缓存?

  1. 假设去掉三级缓存

去掉三级缓存之后,Bean 直接创建 earlySingletonObjects, 看着好像也可以。

如果有代理的时候,在 earlySingletonObjects 直接放代理对象就行了。

但是会导致一个问题:在实例化阶段就得执行后置处理器,判断有 AnnotationAwareAspectJAutoProxyCreator 并创建代理对象

这么一想,是不是会对 Bean 的生命周期有影响。

同样,先创建 singletonFactory 的好处就是:在真正需要实例化的时候,再使用 singletonFactory.getObject() 获取 Bean 或者 Bean 的代理。相当于是延迟实例化。

  1. 假设去掉二级缓存

如果去掉了二级缓存,则需要直接在 singletonFactory.getObject() 阶段初始化完毕,并放到一级缓存中。

img

B 和 C 都依赖 A

那有这么一种场景,B 和 C 都依赖了 A。

要知道在有代理的情况下 singletonFactory.getObject() 获取的是代理对象。

img

多次获取代理对象不同

而多次调用 singletonFactory.getObject() 返回的代理对象是不同的,就会导致 B 和 C 依赖了不同的 A。

那如果获取 B 到之后直接放到一级缓存,然后 C 再获取呢?

一级缓存放的是已经初始化完毕的 Bean,要知道 A 依赖了 B 和 C ,A 这时候还没有初始化完毕。

本文参考结合自以下两篇文章:

【彻底搞懂】Spring之三级缓存解决循环依赖问题 - 腾讯云开发者社区-腾讯云 (tencent.com)

【彻底搞懂】Spring之三级缓存解决循环依赖问题 - 腾讯云开发者社区-腾讯云 (tencent.com)


Spring Boot
http://example.com/2023/06/01/Spring家族/Spring Boot/
作者
where
发布于
2023年6月1日
许可协议