order
Life is a glass of wine, sometimes you need to anesthetize yourself, in order to temporarily forget the pain and unhappiness.
Life is a cup of tea. Sometimes we need to savor it carefully before we find that there is sweetness behind the bitterness and astringency.
Spring is a glass of wine, an official document that can't be seen at a glance. It's really hard to swallow.
Spring is a cup of tea. After swimming in the endless source code, we found that it has all kinds of colors, flavors and tastes.
The winner of the College Entrance Examination is the Internet Red in June, and the Spring Empire is a star in the Java world.
The champion has his own "secret books of martial arts" and Spring has his own "cornerstone of empire".
Please accompany this article with Spring, looking for the cornerstone of the empire.
The cornerstone of Empire
Whether it is as big as a country or as small as an individual, it has its own cornerstone of existence. This cornerstone is the core pillar, just as the economic foundation supports the superstructure.
Take BAT as an example, Baidu's search, Ali's electronics company, Tencent's social network. It can be said that this is the foundation of their company, if you want to in these areas and their PK, there is almost no chance of winning.
Spring is absolutely a shining star in the field of Java development, and its tremendous light has even been leading the development direction of Java.
Now that it has developed into an empire, no one should stand up against it. Well, it's okay to stand up. I don't accept any objection. Ha-ha.
So there's a question, please think about what is the cornerstone of the Spring Empire?
People who have used or know Spring will definitely say IoC, AOP, declarative transactions, and so on. All I can say is that these answers are superficial and obviously not distracted.
Well, let me give you an answer. Bean is the cornerstone of this empire. Surely someone will ask what this bean is, so let's look at its definition. Yes, that's the bean definition in Spring.
In Spring, the bean definition is actually an interface, namely BeanDefinition. As I said in my last "Graduation Decade" article, the classes or interfaces we define are actually descriptions of a data structure, so we can directly regard classes or interfaces as a data structure.
The bean definition interface, then, is a data structure that records all the information of a bean, and all Spring's operations on the bean in the later period are based on that information.
If you are not familiar with Spring, it would be a bit confusing to hear the phrase "all the information about bean s". Don't worry. Take the familiar things in life as an example and try to make them clear to everyone.
In the medical industry, every patient will have a medical record, which records the family history of the patient, the patient's personal history, what examinations and results have been done, what treatments have been done and how well they have recovered. Doctors also diagnose and analyze the patient's condition every time.
The more comprehensive the information is, the better it will be recorded. Follow-up treatment plans are based on this information. The bean information in Spring is equal to the patient's medical record information here.
In the public security system, every suspect will also have a file, which records his confession, crime information or some other evidence. The more comprehensive the information is collected, the better. Later judges'sentencing and sentencing also depend on it.
So here, the file that records the case information can be used to match the information of the bean in Spring.
I believe that through these two examples, you have fully understood the role and status of this bean information. So far, though, you may not really know what information it contains. But it doesn't matter. Just remember that it's very important.
Take advantage of this opportunity to expand a little bit:
Here, the medical record information and the file information record some data, so we can think that they correspond to the data structure in the program.
The doctor's treatment plan and the judge's verdict depend on these data to make decisions, so they can be considered to correspond to the algorithm in the procedure.
It can be seen that the data structure determines the algorithm, or that the algorithm is designed based on the data structure.
Therefore, it can be said that data structure is more important than algorithm. Good data structure can simplify the algorithm, but bad data structure can only make the algorithm more complex.
Follow the change and treat it as a friend
As mentioned in the previous article, the only constant is change, so as time goes on, Spring only needs to add new bean information to the data structure, which Spring uses to define new operations to meet the needs of development.
That's how Spring grew into a vast empire step by step. As I said in my last article, data structures such as classes or interfaces must be carefully designed so that the code is easier to write and easier to change later.
A very obvious example, which started with XML configuration files, is now based on annotations or Java configuration. It can be said that Spring has completed a gorgeous turn, and it is perfectly silky, without any slippage.
In fact, it is to add annotations and Java configuration-related information to the bean definition data structure. Spring uses these information to re-implement it, and coexists with XML-based implementation, so it can use both XML and annotations.
As I said in the previous article, we must be reasonable and abstract, grasp the macro-overall, and define the overall architecture or structure well. As for some specific details of local implementation, we can decide according to the actual situation.
Because local implementations generally cover a small area, it is relatively easy to re-implement them later in a new way. From XML to annotations, this is basically the case.
In fact, to tell the truth, the last article was separated from this one, which was used as an ambush pen and paving the way for this article. Ha-ha.
With so much talk going on, let's take a look at the real face of Lushan Mountain.
The most annoying thing is the source code.
There is a saying, "If it weren't for life, who would like to make himself full of talent". Haha, think about this sentence when you look at the source code.
If you don't want to see it, just skip it.
The BeanDefinition interface and the bean definition are listed below, but there are also set methods:
bean definitions can be inherited
String getParentName();
The class name corresponding to the bean, which is used to instantiate the bean
String getBeanClassName();
Lifecycle Scope
String getScope();
Whether to delay instantiation
boolean isLazyInit();
Other Beans Dependent on
String[] getDependsOn();
Is it a candidate bean for automatic assembly?
boolean isAutowireCandidate();
Whether it is primary, which is used in the case of multiple candidate bean s.
boolean isPrimary();
A factory bean name to generate the bean
String getFactoryBeanName();
A factory method name to produce the bean
String getFactoryMethodName();
The constructor of bean s
ConstructorArgumentValues getConstructorArgumentValues();
Some key/value attributes that can be set to bean s after they are instantiated
MutablePropertyValues getPropertyValues();
Initialization method name
String getInitMethodName();
Destruction method name
String getDestroyMethodName();
Roles, Application Layer/Infrastructure Layer
int getRole();
Human Readable Description
String getDescription();
Is it a single case?
boolean isSingleton();
Prototype
boolean isPrototype();
Abstract
boolean isAbstract();
These two points are more critical. We need to know that:
There are two ways to specify a bean definition, one is the class name and the other is the factory method.
The two life cycles of singleton and prototype are not mutually exclusive, because the existence is neither singleton nor prototype, such as request, session and so on.
AnnotatedBeanDefinition interface extends the bean definition interface and adds annotation-related information:
AnnotationMetadata getMetadata();
MethodMetadata getFactoryMethodMetadata();
ClassMetadata Interfaces are information about classes when they are registered:String getClassName();
boolean isInterface();
boolean isAnnotation();
boolean isAbstract();
boolean isConcrete();
boolean isFinal();
boolean isIndependent();
boolean hasEnclosingClass();
String getEnclosingClassName();
boolean hasSuperClass();
String getSuperClassName();
String[] getInterfaceNames();
String[] getMemberClassNames();
The MethodMetadata interface is the information related to the method when registered through the factory method:
String getMethodName();
String getDeclaringClassName();
String getReturnTypeName();
boolean isAbstract();
boolean isStatic();
boolean isFinal();
boolean isOverridable();
AnnotatedTypeMetadata interface for obtaining attribute information for annotations:
boolean isAnnotated(String annotationName);
Map<String, Object> getAnnotationAttributes(String annotationName);
Map<String, Object> getAnnotationAttributes(String annotationName, boolean classValuesAsString);
MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName);
MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationName, boolean classValuesAsString);
AnnotationMetadata interface for obtaining annotation information on a class:
Set<String> getAnnotationTypes();
Set<String> getMetaAnnotationTypes(String annotationName);
boolean hasAnnotation(String annotationName);
boolean hasMetaAnnotation(String metaAnnotationName);
boolean hasAnnotatedMethods(String annotationName);
Set<MethodMetadata> getAnnotatedMethods(String annotationName);
A small example
The above is too abstract. Let's take a look at it in detail through a simple example.
Register a bean definition of a Boss class with the @Component annotation.
@Component
public class Boss {
}
Use the @Bean method in the @Configuration class to register the bean definitions of two Staff s, and the bean definitions of the Company class will also be registered.
public class Staff {
}
@Configuration
public class Company {
@Bean
public Staff littleMing() {
return new Staff();
}
@Bean
public Staff littleQiang() {
return new Staff();
}
}
When registering a bean definition, you need a bean name, which is automatically generated by default, the class name or method name in lowercase initials.
Therefore, the names of the four bean s defined above are:
boss
company
littleMing
littleQiang
Now that we are here, we should satisfy our curiosity and take out the definition of bean to see what it looks like.
The following is the bean definition of the Boss class:
bossBD = Generic bean: class [org.cnt.ts.bean.Boss];
scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false;
factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in file [G:\workspace\sts4-cnt\taste-spring\target\classes\org\cnt\ts\bean\Boss.class],
-> class org.springframework.context.annotation.ScannedGenericBeanDefinition
You can see that the class name is the full name of the Boss class, so it is registered through the class, so the name of the factory bean and the name of the factory method are null.
The following is the bean definition of the Company class:
companyBD = Generic bean: class [org.cnt.ts.bean.Company$$EnhancerBySpringCGLIB$$d6437e9f];
scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false;
factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null;
defined in file [G:\workspace\sts4-cnt\taste-spring\target\classes\org\cnt\ts\bean\Company.class],
-> class org.springframework.context.annotation.ScannedGenericBeanDefinition
You can see that the class name is the full name of the Company class, but it has been enhanced by CGLIB. So it is registered through classes, so the name of the factory bean and the name of the factory method are null.
The following is the bean definition of Xiaoming's Staff class:
littleMingBD = Root bean: class [null];
scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false;
factoryBeanName=company; factoryMethodName=littleMing; initMethodName=null; destroyMethodName=(inferred);
defined in class path resource [org/cnt/ts/bean/Company.class],
-> class org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader$ConfigurationClassBeanDefinition
As you can see, the class name is null, indicating that it is registered through the factory method, that is, the littleMing factory method of the company factory class.
Here is the bean definition of Xiaoqiang Staff class:
littleQiangBD = Root bean: class [null];
scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false;
factoryBeanName=company; factoryMethodName=littleQiang; initMethodName=null; destroyMethodName=(inferred);
defined in class path resource [org/cnt/ts/bean/Company.class],
-> class org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader$ConfigurationClassBeanDefinition
You can see that the name of the class is null, indicating that it is registered through the factory method, that is, the littleQiang factory method of the company factory class.
Nicknames and Xiaoqiang are registered in exactly the same way, and they are all Staff classes. We should be curious to see if they are the same.
littleMingBD == littleQiangBD -> false
littleMingBD equals littleQiangBD -> false
It is found that the two bean definitions are neither the same nor the same.
Now it's all annotation-based, and naturally you can get annotation information on class superscripts.
On the Boss class is the @Component annotation:
bossAnno = {value=}
On the Company class is the @Configuration annotation:
companyAnno = {value=}
The littleMing() method is the @Bean annotation:
littleMingAnno = {name=[], value=[], initMethod=, autowireCandidate=true, autowire=NO, destroyMethod=(inferred)}
The littleQiang() method is the @Bean annotation:
littleQiangAnno = {name=[], value=[], initMethod=, autowireCandidate=true, autowire=NO, destroyMethod=(inferred)}
Because we don't set the properties of the annotations, all four of the above annotations are defaults.
This article mainly talks about bean definition, remember, bean definition and bean instance (or bean object) are not the same thing, don't confuse.
In fact, our daily business development has little to do with knowing what the bean definition is, just as we usually eat and drink Lasa, as long as we open our mouth to eat and drink, as well as how food is digested and absorbed in the body, generating waste.
But if you want to live healthily and keep healthy, you have to know these things. Similarly, if you want to be a programmer with pursuit and dream, you also need to know the definition of bean.
If a person has no dream, what's the difference between salted fish and salted fish?
Sample code:
https://github.com/coding-new-talking/taste-spring.git
(END)
The author is a farmer who has worked for more than 10 years and is now an architect. Like to research technology, advocate simple and happy. Pursuing the technology of explaining in plain and easy-to-understand language, I hope all readers can understand and remember it. Following is the public number and knowledge planet two-dimensional code, welcome to pay attention!