preface
Learn more about Spring.
Tip: the following is the main content of this article.
BeanDefinition
What is BeanDefinition
- BeanDefinition represents a Bean definition
- Spring creates Bean objects based on the BeanDefinition
- BeanDefinition has many properties to describe a Bean
- BeanDefinition is a very core concept in Spring
Important properties in BeanDefinition
-
beanclass
Represents a bean Type of, for example: UserService.class,OrderService.class,Spring Creating Bean The object will be instantiated according to this attribute during the process of
-
scope
Represents a bean Scope of, such as: If scope be equal to singleton,Then it's time bean It's a single example Bean; If scope be equal to prototype,Then it's time bean It's a prototype Bean.
-
isLazy
Represents a bean Need lazy loading, prototype bean of isLazy Property does not work, lazy loaded singleton bean,For the first time getBean Generate this when bean,Non lazy loading singleton bean,Will be in Spring Generated directly during startup
-
dependsOn
Represents a bean Other that you depend on before creating bean,In a bean Before creating,What it depends on bean You have to create them all first
-
primary
Represents a bean It's the Lord bean,stay Spring There can be more than one type in bean Object, if multiple objects are found according to the type during dependency injection bean,These are judged bean Does a master exist in bean,If it exists, the bean Inject into attribute
-
initMethodName
Represents a bean Initialization method, one bean There is a step in the life cycle called initialization, Spring Will be called in this step bean The initialization logic is controlled by the programmer, which means that the programmer can customize the logic pair bean Processing
BeanFactory
What is BeanFactory
BeanFactory It's a kind of"Spring container", BeanFactory Translated as Bean Factory, As the name suggests, it can be used to create Bean,obtain Bean, BeanFactory yes Spring Very core components in.
Relationship among BeanDefinition, BeanFactory and Bean objects
- BeanFactory will use BeanDefinition to generate Bean objects
- BeanDefinition is equivalent to the raw material of BeanFactory
- Bean objects are equivalent to products produced by BeanFactory
The core sub interfaces and implementation classes of BeanFactory
- ListableBeanFactory
- ConfigurationBeanFactory
- AutoWireCapableBeanFactory
- AbstractBeanFactory
- DefaultListableBeanFactory
Features of DefaultListableBeanFactory
- Support singleton Bean
- Support Bean alias
- Support parent-child BeanFactory
- Support Bean type conversion
- Support Bean post
- Support FactoryBean
- Support automatic assembly
- wait
Bean life cycle
What is a Bean lifecycle
Bean The life cycle describes Spring One in Bean Steps in the creation process and destruction process, where Bean The creation process is the focus. Programmers can use Bean Life cycle mechanism Bean Perform custom machining
Core steps in the Bean cycle
-
BeanDefinition object creation
BeanDefinition express Bean Definition, which defines a Bean Type of, Spring Is to use BeanDefinition To create Bean Yes, for example, it needs to be used BeanDefinition in BeanClass Attribute determination Bean Type to instantiate the object.
-
Construction method inference
One Bean There can be more than one construction method in, which is required at this time Spring To determine which construction method to use. If a class has only one construction method, there is no choice but to use this construction method. If a class has multiple construction methods, it will first judge whether there is one@Autowired Specify the construction method, and then see whether there is a parameter free construction method. If there is none, an error will be reported No default constructor found. After determining a construction method through construction method inference, you can instantiate an object using the construction method.
-
instantiation
An instantiated object is reflected by the construction method Spring In, you can BeanPostProcessor Mechanism to intervene in instantiation
-
Attribute filling
The object obtained by instantiation is an "incomplete" object, which means that some attributes of the object have not been filled in, that is Spring Some attributes have not been assigned automatically. Attribute filling is what we usually call automatic injection and dependency injection.
-
initialization
After the properties of an object are populated, Spring Provides an initialization mechanism that programmers can use to Bean For custom processing, for example, you can use InitialzingBean Interface to Bean Assign values to other properties in, or Bean Check some properties in
-
After initialization
After initialization Bean Create the last step in the lifecycle, as we often say AOP Mechanism is passed in this step BeanPostProcessor Mechanism, and the object obtained after initialization is the real object Bean Object.
@Autowired
@What is Autowired
@Autowired It indicates whether a certain attribute needs dependency injection. It can be written on attributes and methods. In annotation required Property defaults to true,Indicates that an exception is thrown if no object can be injected into the property.
@Workflow of Autowired
The complete underlying filtering logic steps are more than just these two steps
@Autowired is added to an attribute
@Service public class OrderService{ @Autowired private UserService userService; }
@Autowired Added to an attribute, Spring In progress Bean During the life cycle of, in the step of attribute filling, the attribute will be added to the object based on the instantiated object@Autowired The attribute of is automatically assigned a value to the attribute.
Spring According to the type of attribute Spring Find all of this type in the container Bean Object. If multiple objects are found, one of them will be determined according to the name of the attribute. If required Attribute is true,If the object cannot be found according to the attribute information, an exception is thrown directly
@Autowired is added to a method
@Service public class OrderService{ private UserService userService; @Autowired public void setUserService(UserService userService) { this.userService = userService; } }
When@Autowired When an annotation is written on a method, Spring stay Bean In the attribute filling phase of the life cycle, the parameter type and parameter name of the method will be changed from Spring The container finds the object as a method input parameter and automatically calls the method.
@Autowired is added to the construction method
@Service public class OrderService{ private UserService userService; @Autowired public OrderService(UserService userService) { this.userService = userService; } public OrderService(UserService userService, UserService userService) { this.userService = userService; } }
@Autowired When added to the construction method, Spring The constructor will be selected for instantiation in the infer constructor stage. Before calling the constructor by reflection, the parameter name will be changed from Spring Found in container Bean Object as a constructor.
@Resource
@What is a Resource
@Resource Annotation and@Autowired Similarly, it is also used for dependency injection,@Resource yes Java Notes provided at the level,@Autowired yes Spring The annotations provided are also different from the underlying implementation logic of dependency injection.
@Workflow of Resource
@There is a name attribute in the Resource annotation. Whether the name attribute has a value or not, the dependency injection underlying process of @ Resource is different
@Resource If name Property has a value, then Spring Will be directly based on the specified name Value go Spring Container find Bean Object. If it is found, it succeeds. If it is not found, an error is reported
@If the Resource name attribute has no value
- First judge whether the attribute name has a Bean object in the Spring container.
- If it exists, the Bean object is successfully found for injection.
- If it does not exist, go to the Spring container to find the Bean object according to the attribute type, and inject it if one is found.
@Value
@What is Value
@Value Notes and@Resource,@Autowired Similarly, it is also used for dependency injection on attributes, but@Value It's used to get Properties File, and@Value Can parse SpEl(Spring Expression).
@Workflow of Value
@Value("cq")
String directly"cq"Assign to attribute if the attribute type is not String,Or the type conversion cannot be performed, an error is reported.
@Value("${cq}")
Will put ${}String in as key,from Properties Find the corresponding in the file value Assign a value to the attribute. If it is not found, it will"${cq}"Inject the property as an ordinary string
@Value("#{cq}")
Will#The string in {} is parsed as a spring expression. Spring will take "cq" as beanName and find the corresponding bean from the spring container. If it is found, property injection will be carried out. If it is not found, an error will be reported.
FactoryBean
What is a FactoryBean
FactoryBean yes Spring Provides a more flexible way to create Bean Can be achieved by FactoryBean In the interface getObject()Method to return an object, which is the final object Bean Object.
Methods in FactoryBean interface
-
Object getObject(): returns a Bean object
-
boolean isSingleton(): judge whether the returned is a singleton Bean object
-
Class getObjectType(): returns the type of Bean object
Special points of FactoryBean
@Component("cq") public class CqFactoryBean implements FactoryBean{ @Override // Bean object public Object getObject() throws Exception { return new User(); } @Override // Type of Bean object public Class<?> getObjectType() { return User.class; } @Override // Is the defined Bean a singleton or a prototype public boolean isSingleton() { return true; } }
The above code actually corresponds to two Bean objects:
- beanName is "cq", and the bean object is the User object returned by the getObject method.
- beanName is "& CQ", and the bean object is an instance object of CqFactoryBean class.
Difference between FactoryBean and BeanFactory
FactoryBean
The FactoryBean object itself is also a Bean. At the same time, it is equivalent to a small factory, which can produce other beans.
BeanFactory
Bean factory is a Spring container and a large factory, which can produce a variety of beans.
ApplicationContext
What is ApplicationContext
ApplicationContext Yes than BeanFactory More powerful Spring Container, which can create bean,obtain bean,It also supports internationalization, event broadcasting, access to resources, etc BeanFactory Not available.
Interface inherited by ApplicationContext
-
EnvironmentCapable
ApplicationContext Inheriting this interface means that it has the function of obtaining environment variables, which can be accessed through ApplicationContext Get operating system environment variables and JVM Environment variables.
-
ListableBeanFactory
ApplicationContext If you inherit this interface, you have the right to get all the information beanNames,Judge a beanName Does it exist beanDefinition Object and statistics BeanDefinition Number of. Get all corresponding to a type beanNames And other functions.
-
HierarchicalBeanFactory
ApplicationContext If you inherit this interface, you have the access parent BeanFactory,Judge a name Does it exist bean Object.
-
MessageSource
ApplicationContext If you inherit this interface, you will have the internationalization function. For example, you can use it directly MessageSource Object to get an internationalized resource(For example, the characters corresponding to different national languages)
-
ApplicationEventPublisher
ApplicationContext By inheriting this interface, you have the event publishing function and can publish events. This is ApplicationContext be relative to BeanFactory More prominent and commonly used functions.
-
ResourcePatternResolver
ApplicationContext If you inherit this interface, you have the function of loading and obtaining resources. The resources here can be files, pictures, etc URL All resources are OK.
BeanPostProcessor
What is BeanPostProcessor
BeanPostProcessor is an extension mechanism provided by Spring, which can be used to customize beans. It is also widely used in the implementation of Spring's underlying source code. BeanPostProcessor is usually also called Bean post processor.
BeanPostProcessor stay Spring Medium is- -Two interfaces, we define- -A post processor is provided- -A class implements the interface in Spring There are also some interfaces that inherit BeanPostProcessor,These sub interfaces are BeanPostProcessor Basis of.Some other functions have been added to the.
Methods in BeanPostProcessor
- Postprocessbeforeinitialization(): pre initialization method, which means that this method can be used to customize Bean processing before initialization.
- Postprocessafterlocalization(): method after initialization, which means that this method can be used to customize Bean processing after initialization.
InstantiationAwareBeanPostProcessor
A sub interface of BeanPostProcessor
- Postprocessbeforeinstance(): before instantiation
- Postprocessafterinstance(): after instantiation
- postProcessProperties(): after property injection
AOP
What is AOP
AOP is aspect oriented programming. It is very suitable for adding unified functions to one or some businesses without modifying the business code, such as logging, permission control, transaction management, etc. it can decouple the code and improve the development efficiency.
Core concepts in AOP
-
Advice
Advice can be understood as notification and suggestion. In Spring, the proxy logic is defined by defining advice.
-
Pointcut
Pointcut is the tangent point, indicating which class and method the agent logic corresponding to Advice is applied to.
-
Advisor
Advisor is equal to Advice+Pointcut, which represents a whole of agent logic and pointcut. Programmers can define pointcut and agent logic by defining or encapsulating an advisor.
-
Weaving
Weaving means weaving. The process of embedding Advice agent logic into pointcuts at the source code level is called weaving.
-
Target
Target represents the target object, that is, the proxy object. The target object will be held in the proxy object generated by AOP.
-
Join Point
The Join Point represents the connection point. In Spring AOP, it is the execution point of the method.
How AOP works
AOP occurs during the life cycle of a Bean
- When Spring generates a bean object, it first instantiates an object, that is, a target object
- Then fill in the attribute of the target object
- In the post initialization step, you will judge whether the target object has a corresponding section
- If there is a slice, it means that the current target object needs AOP
- A proxy object is generated by Cglib or JDK dynamic proxy mechanism as the final bean object
- A - target attribute in the proxy object points to the target object
summary
Tip: here is a summary of the article:
Some notes of spring Bean are understood and explained