Spring has revolutionized the Java world view. Spring solves the Java object management problem, and today we’ll take a look at some of the ways spring creates objects that we don’t know yet

Several ways to register beans (IOC)

BeanDefinition

  • If we look at the class diagram,BeanDefinitionRegistryThere are three implementation classes below. Spring provides us with a defaultBeanDefinitionRegistration factoryDefaultListableFactory. The reason it’s Default is not just because the name has the word Default in it. But in theAnnotationConfigApplicationContextThe default is DefaultListableFactory. Develop summaries in annotationAnnotationConfigApplicationContextContext is often used. It can also be understood as a Spring container.

The configuration class Config

  • I’m sure you’ve all used SpringBoot. In SpringBoot, you first need a boot class. The startup class is decorated with various annotations. It is a configuration portal. Equivalent to the XML configuration file in Spring.
  • We need a configuration class like this for demonstration purposes. Tell Spring which classes he needs to do load parsing.

@ComponentScan(value = "com.zxhtom.cloud.order.spring")
public class Config {}Copy the code
  • What Config does is tell Spring to scancom.zxhtom.cloud.order.springClasses with Spring annotations and configuration classes under the package

Generated bean

  • I believe you are right@Bean,@Component,@ServiceThese notes are familiar. These are spring Bean annotations. But what’s behind the notes? Right! That’s the subject of this chapterBeanDefinition. Spring’s bean registration is done through it.
// Get the container context first
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
// Generate the BeanDefinitionBuilder corresponding to the Java class
BeanDefinitionBuilder builder = BeanDefinitionBuilder
        .genericBeanDefinition(Student.class);
// Register BeanDefinition with the Spring container
context.registerBeanDefinition("student",builder.getBeanDefinition());
// Try to get
Object orderController = context.getBean("student");
System.out.println(orderController);

Copy the code

  • A few lines above complete the registration of the springbean. In AnnotationConfigApplicationContext, we see he is inherited GenericApplicationContext of this class. The default in this class is the DefaultListableFactory we mentioned above

  • This is also the picture we put in the beginning. At this point we know that BeanDefinition is an element of the Spring registered bean. The BeanDefinitionRegistry is the registration of real workers. He is responsible for parsing BeanDefinition and converting the corresponding Java objects into Spring beans. There are many, many details. We’re not going to do expansion here.

FactoryBean

  • FactoryBean is an interface, and in Java8 we only need to implement getObject and getObjectType. The former is the generated object and the latter is the returned object Class object.

  • Let’s create a springbean using FactoryBean.


@Data
public class User {
    private String name;
}

Copy the code
  • ① First let’s write a plain Java class, User. Do not add annotations to Spring registered beans

public class UserFactoryBean implements FactoryBean<User> {
    @Override
    public User getObject(a) throws Exception {
        User user = new User();
        user.setName("hello");
        return user;
    }

    @Override
    publicClass<? > getObjectType() {returnUser.class; }}Copy the code
  • ② Then write an implementationFactoryBeanThe implementation class of the interface. In the getObject method we construct a User object and return it.

public class BeanTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        BeanDefinitionBuilder builder = BeanDefinitionBuilder
                .genericBeanDefinition(UserFactoryBean.class);
        context.refresh();
        context.registerBeanDefinition("user", builder.getBeanDefinition());
        System.out.println("Access to the user."+context.getBean("user"));
        System.out.println("Get userFactoryBean."+context.getBean("&user")); }}Copy the code
  • Finally, we build a BeanDefinition object corresponding to UserFactoryBean. Note that the BeanDefinition of UserFactoryBean registers two objects with Spring into the Spring container. One is the object in the getObject method. The other is the UserFactoryBean itself.

  • In the Spring container, object information is stored in KV form. It is impossible for two objects to correspond to the same key. The name registered above is user.

key object
user The User object
&user UserFactoryBean object
  • FactoryBeanThe role is to code the bean generation process in charge. For example, build a User object to register with the Spring container. This requirement is added directly to the User class@ComponentAdd a scan path to the Springboot boot class.
  • However, if the name in the User object needs to be assigned the current time to name at startup, we can’t easily configure this requirement with the annotations provided by Spring. But byFactoryBeanIt can be solved very well. Because we get the time from the code container and assign it.
  • FactoryBeanIt also has a high status in Spring. How to register Mapper interface with Spring container in Mybatis framework is to use his function. There is no way to register an interface in Spring. Mybatis registers the interface generation proxy class with the Spring container. During the execution of these proxy classes, SQL Session is executed based on SQL in the XML of Mapper objects for data parsing.

Supplier

  • inGenericApplicationContextClass we find thatregistryBeanMethod requires Class, Supplier, and BeanDefinitionCustomer parameters.

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.refresh();
    context.registerBean("user", User.class);
    User user = (User) context.getBean("user");
    System.out.println(user.getName());
}

Copy the code
  • Again, I need to register whether to assign the current time to the User#name property. At this point, routine operations are not sufficient. At this time except as mentioned aboveFactoryBeanIn addition, we can initialize through Supplier.

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    context.refresh();
    context.registerBean(User.class, new Supplier<User>() {
        @Override
        public User get(a) {
            User user = new User();
            user.setName(new Date().toString());
            returnuser; }},new BeanDefinitionCustomizer() {
        @Override
        public void customize(BeanDefinition bd) {
            bd.setPrimary(true); System.out.println(bd); }}); User user = (User) context.getBean("user");
    System.out.println(user.getName());
}

Copy the code
  • The above code implements the initial registration of the User object properties. The BeanDefinition will be enhanced and updated. In Spring Customizer often means code encapsulation.BeanDefinitionCustomizerIs theBeanDefinitionThe encapsulation of objects facilitates secondary operations on them.

spring AOP

  • AOP full name Aspect Oriented Programming abbreviation. In Spring we are used to faceted programming. Facets really help us achieve a lot of help. He took away our repetitive work, and our entire business was no longer linearly programmed. Eventually our development process will become module -> AOP -> module

concept

  • There are a few terms we need to know about AOP

  • -Serena: I know

  • Joint point: indicates the connection point. Handling exceptions

  • Pointcut: a Pointcut. Define intercept points. By the point of dough

  • Advice: Wrap execution points with enhancements at pointcuts

  • Target: the real object of the proxy object

  • Weaving: Connect aspects

Knowledge of the Spring container

  • The two main spring features we demonstrated above. The IOC + AOP. IOC is about registering Java objects into the container through reflection. So what the hell is this container? So let’s just call it KV. Inside is a map. key which is the beanName of the Java object in the container. Value is the Java object itself.

It is better to teach people how to fish than to teach them how to fish. Spring is powerful and I believe anyone who has done Java development knows that. Today we start the first word of Spring related courses — overall review, we will also start from the five aspects in the future. As there are many unknowns in the framework itself, the summary in it must refer to other literatures. Personal summary

Spring structure

Core Container

The Core Container in Spring contains Core, Beans, Context, and Expression Language modules. Core and Beans modules are the foundation of the framework and provide IoC (Reverse control) and dependency injection features. The underlying concept here is the BeanFactory, which is a gold standard implementation of the Factory pattern to eliminate the need for programmatic simplicity patterns and really allow you to separate dependencies and configurations from your program logic.

Core

The core module contains the basic core utility classes of the Spring framework, which are used by all Spring components. Core is the underlying file, and any Spring product is built on top of core.

Beans

Beans is an extension of Core. It contains classes for accessing configuration files, creating and managing Beans, and performing inversion of control and dependency injection operations. Beans are equivalent to a functional offering. All Spring projects use this functionality. This introduces dependency injection (Inversion of control), one of Spring’s big features

Context

The Context module builds on Core and Beans modules and provides a box-like object access method similar to the framework DI registry. The Context module inherits Beans features and provides a number of extensions to the Spring core, adding support for internationalization (such as resource binding), event propagation, resource loading, and transparent creation of Co nText. The Context module also supports some J2EE features, 171) :Ji. Port EJB, machine and basic remote processing. The ApplicationContext interface is the key to the Context module.

The Expression Language module provides a powerful Expression Language for querying and manipulating objects at run time.

The Expression Language module provides a powerful Expression Language for querying and manipulating objects at run time. It is an extension of the Unifed Expression Language defined in the JSP 2.1 specification. The language supports setting/obtaining property values, assigning properties, calling methods, accessing accessiong the Context of Arrays, containers and indexers, logical and arithmetic operators, named variables, and name-checking from IoC containers in the SPerrit The line object. It also supports list projection, selection, and general list aggregation

Data Access/Integration

The Data Access/Integration layer contains BC, ORM, OXM, base, and Transaction modules.

  • The JDBC module provides a JDBC abstraction layer that eliminates the verbose JDBC encoding and error code specific to the database vendor. This module contains all the classes that Spring encapsulates for JDBC data access.
  • ORM module is a popular object-relational mapping API, such as JPA, JDO, Hibernate, Mybatis. Provides an interaction layer. With ORM packages, you can mix and match all the features provided by Springboot for OR mapping

The Spring framework inserts several ORM frameworks to provide object-relational tools for ORM, including JDO, Hibernate, and iBatisSQL Map. All follow Spring’s common transaction and DAO exception hierarchies

  • The OXM module provides an abstraction layer for ObjecνXML mapping implementations, including JAXB, Castor, XMLBeans, JiBX, and XStrearn.
  • The Java Messaging Service (JMS) module mainly contains some features for making and consuming messages.
  • The Transaction module supports programmatic and declarative Transaction management, and these Transaction classes must implement specific interfaces and be applicable to all POJOs.

Web

The Web context module builds on the application context module. Provides context for Web-based applications. So the Spring framework supports integration with Jakarta Struts. The Web module also simplifies the processing of most requests and binds request parameters to domain objects. The Web layer contains Web, Servlet, Struts, and portlet modules.

  • Web Modules: Web-oriented integration features for child labor basics. Multiple file uploads, IOC containers and container context initialization using Listeners. It also includes web-related parts of Spring’s remote support.
  • Servlet module: This module contains Spring’s model-View-Controller (MVC) implementation. Spring’s MVC framework provides a clear separation between model-scoped code and Web Forms

And integrate with other features of the Spring framework

  • Struts module: this module provides support for Struts, enabling classes in the Springboot container to be integrated with a typical Struts web layer, which has been discarded since spring3.0
  • Portlet module: Provides an implementation of Mvc for the Portlet environment and the Web-servlet module

Aop

The AOP module provides an implementation of section-oriented programming that complies with the AOP Consortium standards, allowing you to define things like method interceptors and pointcuts to separate logical code and reduce compatibility between them. Using source-level metadata, you can also incorporate behavioral information into your code, a bit like the attribute concept in.NET technology. Through the configuration management feature, SpringAOP modules integrate section-oriented programming functionality directly into the Spring framework, so you can easily make any object managed by the Spring framework AOP enabled. The Spring AOP module provides transaction management services for objects in Spring-based applications. Using SpringAOP, you can integrate audible transaction management into your application without relying on EJB components. The Aspects module provides integration support for AspectJ. . The Instrumentation module provides class Instrumentation support and a ClassLoader implementation that can be used on specific application servers.

Test

The Test module does unit tests inside a container. There’s nothing to tell.

Singleton pool the BeanFactory ApplicationContext AnnotationConfigApplicationContext ClassPathXmlApplicationContext FileSystemApplicationContext

conclusion

  • Spring is a framework, but now spring is more than just a framework. We can think of Spring as an ecology.

  • The scaffolding SpringBoot has been derived from Spring. And SpringCloud on microservices

  • In springcloud there are many components that are derived. Much of it borrows from Netflix. Such as Eureka, Zuul, etc. Zuul has been replaced by SpringCloud Gateway

  • Spring’s design is already well integrated with Mybatis, Redis and RabbitMQ.

  • This chapter focuses on Spring. We will continue to update the Spring Cloud topic. Because finding in the Cloud requires a lot of spring fundamentals.

  • Cloud will be released first this May Day. Have a spring fling. See you after May Day