Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deeply parse the Spring5.0 source code

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail for you how to deeply analyze the Spring5.0 source code, the content of the article is of high quality, so the editor shares it for you to do a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Principle of Spring Core Annotation

This article mainly analyzes the core annotations of Spring.

One: @ Condition comment

Condition is a conditional comment added to spring4.0, through which you can selectively inject Bean. Next, learn how to use Condition, and then analyze the spring source code to understand the implementation principle.

Implementation case:

In Spring container loading, win7 entity classes are assembled if the current environment is the WIN7 operating system, and other systems are not assembled.

@ Configurationpublic class MyConfig {/ * Import mainly injects external jar packages into the springioc container @ Import (Win7Entity.class) equals that the bean object id registered with @ Bean * Import is the current class full path * / @ Bean public Win7Entity win7Entity () {return new Win7Entity ();} public class V1Spring {public static void main (String [] args) {/ / 1. Based on annotation, ApplicationContext annotationApplicationContext = new AnnotationConfigApplicationContext (MyConfig.class); Win7Entity win7Entity = (Win7Entity) annotationApplicationContext.getBean ("win7Entity"); System.out.println (win7Entity)

Output result

Com.mayikt.v1.entity.Win7Entity@5606c0b

MyCondition

Public class MyCondition implements Condition {/ * @ param context gets the current context * @ param metadata to get the careful * @ return * / public boolean matches (ConditionContext context, AnnotatedTypeMetadata metadata) {/ / 1. Get the current environment Environment environment = context.getEnvironment (); / / win7 linux win8 win10 Apple system MAC String osName = environment.getProperty ("os.name"); if (osName.equals ("Windows 10")) {/ / can register the object return true;} / / cannot register the object return false } @ Configurationpublic class MyConfig {/ * Import mainly injects external jar packages into the springioc container @ Import (Win7Entity.class) equals to the current full class path of the bean object id registered with @ Bean * Import * / @ Bean @ Conditional (MyCondition.class) public Win7Entity win7Entity () {return new Win7Entity ();}

Output:

Com.mayikt.v1.entity.Win7Entity@64d7f7e0

Two: @ Import comment

1. Why use @ Import annotations? The main purpose of Import annotations is to inject external jar packages into the springioc container

What is the application scenario of 2.@Bean annotations? Register to load external jar packages

@ Configuration@Import (Win7Entity.class) public class MyConfig {/ * Import mainly injects external jar packages into the springioc container @ Import (Win7Entity.class) is equivalent to @ Bean * Import registered bean object id is the current class full path * / / * @ Bean @ Conditional (MyCondition.class) public Win7Entity win7Entity () {return new Win7Entity () } * / public class V1Spring {public static void main (String [] args) {/ / 1. Based on the annotation method, start ApplicationContext annotationApplicationContext = new AnnotationConfigApplicationContext (MyConfig.class); Win7Entity win7Entity = (Win7Entity) annotationApplicationContext.getBean ("com.mayikt.v1.entity.Win7Entity"); / / the full-path System.out.println (win7Entity) of the current class Win7Entity

Results:

Com.mayikt.v1.entity.Win7Entity@f4168b8

Public class V1Spring {public static void main (String [] args) {/ / 1. Based on annotation, ApplicationContext annotationApplicationContext = new AnnotationConfigApplicationContext (MyConfig.class); Win7Entity win7Entity = (Win7Entity) annotationApplicationContext.getBean ("com.mayikt.v1.entity.Win7Entity"); System.out.println (win7Entity); String [] beanDefinitionNames = annotationApplicationContext.getBeanDefinitionNames (); for (int I = 0; I)

< beanDefinitionNames.length; i++) { System.out.println(beanDefinitionNames[i]); } 结果 com.mayikt.v1.entity.Win7Entity@f4168b8org.springframework.context.annotation.internalConfigurationAnnotationProcessororg.springframework.context.annotation.internalAutowiredAnnotationProcessororg.springframework.context.annotation.internalRequiredAnnotationProcessororg.springframework.context.annotation.internalCommonAnnotationProcessororg.springframework.context.event.internalEventListenerProcessororg.springframework.context.event.internalEventListenerFactorymyConfigcom.mayikt.v1.entity.Win7Entity 总结下:@Bean注解与@Import注解的区别? @Bean注解注册的bean的id是以方法名称来作为beanid , @Import注解以当前类的完整路径地址注册 ,相比来说@Import注入类更加简单 应用场景都是引入外部jar包 三@EnableXXX注解的实现原理 配合@Configuration使用,包括 @EnableAsync, @EnableScheduling, @EnableTransactionManagement, @EnableAspectJAutoProxy, @EnableWebMvc。 @Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@Import({PayEntity.class,MyPayEntity.class}) //引入@Import注解public @interface EnablePayEntity { // 只要启动的时候 加入该EnablePayEntity 就会将PayEntity实体类注入到spruingioc容器 // Enable注解的话 底层 实际上在调用@Import(PayEntity.class)}@Configuration@Import(Win7Entity.class)@EnablePayEntity //配置类加上这个注解public class MyConfig { /** * Import作用主要将外部的jar包注入到springioc容器中 @Import(Win7Entity.class) 等于与@Bean * Import注册的bean对象 id为当前类全路径 */ 程序输出结果 com.mayikt.v1.entity.Win7Entity@130f889org.springframework.context.annotation.internalConfigurationAnnotationProcessororg.springframework.context.annotation.internalAutowiredAnnotationProcessororg.springframework.context.annotation.internalRequiredAnnotationProcessororg.springframework.context.annotation.internalCommonAnnotationProcessororg.springframework.context.event.internalEventListenerProcessororg.springframework.context.event.internalEventListenerFactorymyConfigcom.mayikt.v1.entity.PayEntitycom.mayikt.v1.entity.MyPayEntitycom.mayikt.v1.entity.Win7Entity @EnableXXX注解的实现原理:底层实际上还是调用@Import注解 四:ImportSelector类public class MyImportSelector implements ImportSelector { /** * 注解信息 * @param importingClassMetadata * @return */ public String[] selectImports(AnnotationMetadata importingClassMetadata) { //注入多个对象,类的完整路径 return new String[]{"com.mayikt.v1.entity.MemberEntity","com.mayikt.v1.entity.MsEntity"}; }}@Configuration@Import({Win7Entity.class,MyImportSelector.class})@EnablePayEntitypublic class MyConfig { /** * Import作用主要将外部的jar包注入到springioc容器中 @Import(Win7Entity.class) 等于与@Bean * Import注册的bean对象 id为当前类全路径 */ 输出结果 com.mayikt.v1.entity.Win7Entity@16267862org.springframework.context.annotation.internalConfigurationAnnotationProcessororg.springframework.context.annotation.internalAutowiredAnnotationProcessororg.springframework.context.annotation.internalRequiredAnnotationProcessororg.springframework.context.annotation.internalCommonAnnotationProcessororg.springframework.context.event.internalEventListenerProcessororg.springframework.context.event.internalEventListenerFactorymyConfigcom.mayikt.v1.entity.PayEntitycom.mayikt.v1.entity.MyPayEntitycom.mayikt.v1.entity.Win7Entitycom.mayikt.v1.entity.MemberEntitycom.mayikt.v1.entity.MsEntity五:ImportBeanDefinitionRegistrarpublic class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { /** * AnnotationMetadata 注解的信息 * @param importingClassMetadata * @param registry */ public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { // spring容器中 bean 的信息 Bean Definition描述 手动注册到ioc容器中 RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(SmsEntity.class); registry.registerBeanDefinition("smsEntity", rootBeanDefinition); // 底层源码:springioc 底层通过beanDefinitionMap存放 线程是安全的 } //FactoryBean (往IOC容器存储对象 注入对象) BeanFactory(从ioc工厂获取bean对象)}底层实现原理:

This.beanDefinitionMap.put (beanName, beanDefinition); private final Map beanDefinitionMap = new ConcurrentHashMap

The underlying layer is stored through a ConcurrentHashMap.

@ Configuration@Import ({Win7Entity.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class}) @ EnablePayEntitypublic class MyConfig {/ * Import mainly injects external jar packages into the springioc container @ Import (Win7Entity.class) equals that the bean object id registered with @ Bean * Import is the current full class path * /

Output result

MyConfigcom.mayikt.v1.entity.PayEntitycom.mayikt.v1.entity.MyPayEntitycom.mayikt.v1.entity.Win7Entitycom.mayikt.v1.entity.MemberEntitycom.mayikt.v1.entity.MsEntitysmsEntitysix: FactoryBeanpublic class MyFactoryBean implements FactoryBean {public MyEntity getObject () throws Exception {return new MyEntity ();} public Class getObjectType () {Entity6. } / / the object public boolean isSingleton () {/ / is injected into the IOC container. By default, it is represented by true true as a single false and as multiple return false. }} @ Configuration@Import ({Win7Entity.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class,MyFactoryBean.class}) @ EnablePayEntitypublic class MyConfig {/ * Import mainly injects external jar packages into the springioc container @ Import (Win7Entity.class) equals that the bean object id registered with @ Bean * Import is the current full class path * /

Output result

MyConfigcom.mayikt.v1.entity.PayEntitycom.mayikt.v1.entity.MyPayEntitycom.mayikt.v1.entity.Win7Entitycom.mayikt.v1.entity.MemberEntitycom.mayikt.v1.entity.MsEntitycom.mayikt.v2.config.MyFactoryBeansmsEntity question: the difference between BeanFactory and FactoryBean?

BeanFactory is a Factory, that is, an IOC container or object factory, and FactoryBean is a Bean. In Spring, all Bean is managed by BeanFactory (that is, the IOC container).

But for FactoryBean, this Bean is not a simple Bean, but a factory Bean that can produce or modify object generation, and its implementation is similar to the factory pattern and modifier pattern in the design pattern.

Question: the difference between @ Service and @ Compent annotations?

The bottom layer still calls @ Compont annotations, mainly for classification and better division of scenarios. Pay attention to the scope of sweeping packages.

@ Target ({ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Componentpublic @ interface Mayikt {} Spring comment @ Qualifie

We have already come into contact with @ Qualifier when learning @ Autowired, so let's take a closer look at customizing @ Qualifier in this section.

For example, define a vehicle class: Vehicle, and its subclasses Bus and Sedan.

If you use @ Autowired to find Vehicle, there are two matching options Bus and Sedan. To limit the options, you can do something like this.

@ Autowired@Qualifier ("car") private Vehicle vehicle

If you want to use @ Qualifier ("car") frequently and want to make it more meaningful, we can customize an @ Qualifier.

@ Target ({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE}) @ Retention (RetentionPolicy.RUNTIME) @ Qualifierpublic @ interface Car {} @ Autowired @ Car private Vehicle vehicle; finally annotates the Sedan class. @ Carpublic class Sedan implements Vehicle {} question: the difference between @ Primary and @ Qualifier?

What's the problem when there are two implementation classes under one interface that use @ Autowired to get it?

@ Autowired uses type lookup by default, which is problematic. SpringBoot multiple data sources set the default or priority.

Solution:

@ Resource look up by name

@ Qualifier specifies the implementation class

@ Primary specifies the priority of the implementation class first, which is obtained by default

On how to deeply analyze the Spring5.0 source code to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report