This article has participated in the Denver Nuggets Creators Camp 3 “More Productive writing” track, see details: Digg project | creators Camp 3 ongoing, “write” personal impact.

Why use Spring5

Over the years, Spring has become the established enterprise J2EE standard. Its greatest strength is its lightweight and core IOC container. The latest release of Spring is 5.3.9, and Spring5 offers many new features, three of which I think are the most important:

  • Use the new features in JDK8

Most notably, Spring5 uses lambda expressions in JDK8 to make the code more concise.

  • Responsive programming support

One of the main features of Spring5 is reactive programming, which provides an alternative programming style that focuses on building applications that respond to events. Spring5 includes a response flow and a Reactor.

  • Responsive Web frameworks

Spring5 provides a new responsive Web framework, Spring WebFlux, which differs from previous traditional Web frameworks in terms of programming philosophy and usage habits.

Of course, we need to embrace new technologies and new changes, so come and learn Spring5.

What is an IOC container

IOC is also known as dependency injection (DI). It is the process by which an object defines its dependencies (that is, other objects it works with) through properties set on an object instance constructed or returned from a factory method, using only constructor arguments, arguments to a factory method, or other objects it works with.

In simple terms, objects are constructed from configured parameters and then instantiated from configured properties. Instead of using the usual Java New methods to create objects, and without having to manually find or instantiate dependent objects, everything is done through the Spring IOC container.

The IOC container two main bag is: org. Spring framework. Beans and org. Springframework. The context.

If you want to use an IOC container, the following two dependencies are required:

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.3.9. RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.9. RELEASE</version>
    </dependency>
Copy the code

There are two very important classes in the IOC container: BeanFactory and ApplicationContext.

ApplicationContext is a subclass of BeanFactory, which provides an interface for manipulating beans. ApplicationContext represents the container itself, and provides other aspects of Bean operations such as AOP access, event handling, Useful features such as message resource access and application context.

Org. Springframework. Context. ApplicationContext interface represents a SpringIOC container, it is responsible for instantiating, configure, and assemble the bean. The container reads configuration metadata to get instructions about objects to instantiate, configure, and assemble. Configuration metadata is represented in XML, Java comments, or Java code. It defines the objects that make up the application and the rich dependencies between those objects.

If you are creating a single application, Spring provides two useful ApplicationContext, ClassPathXMLApplicationContext or FileSystemXMLApplicationContext.

ClassPathXMLApplicationContext from route to class loading to load the configuration of the FileSystemXMLApplicationContext from the path to the file to load.

You just define the business objects (POJos) you need to use in the configuration, and after you create and initialize the ApplicationContext, you have a fully configured and executable system or application.

Configuring metadata

Configuration configuration, the essence of Spring is to expose and build business objects through configuration. Normally, you can do this using XML files, but now you can also use Java annotations and Java code.

The Spring configuration consists of at least one or more bean definitions that the container must manage. Xml-based configuration metadata is typically used to represent. Java configurations typically use the @Bean annotation method in @Configuration.

Here is a basic XML-based definition of daos.xml:


      
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="accountDao"
          class="com.flydean.daos.JpaAccountDao">
        <! -- additional collaborators and configuration for this bean go here -->
    </bean>

    <bean id="itemDao" class="com.flydean.daos.JpaItemDao">
        <! -- additional collaborators and configuration for this bean go here -->
    </bean>

    <! -- more bean definitions for data access objects go here -->

</beans>
Copy the code

Where id is the bean’s unique identifier and class is the bean’s classpath.

Instantiate container

The Spring container has a variety of instantiation methods, such as the singleton application’s two classes described above:

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml"."daos.xml");
Copy the code

Daos.xml was listed above, so let’s list services.xml again:


      
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">

    <! -- services -->

    <bean id="petStore" class="com.flydean.services.PetStoreService">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <! -- additional collaborators and configuration for this bean go here -->
        <constructor-arg ref="accountDao"/>
    </bean>

    <! -- more bean definitions for services go here -->

</beans>
Copy the code

Service. XML mainly defines references to beans defined in daos.xml. Ref. Ref refers to the id of the bean in daos.xml.

Nested XML

In addition to loading multiple XML files when creating the ApplicationContext in the example above, we can also import other XML files in the XML by importing them.

    <import resource="daos.xml"/>
Copy the code

Resource configures the path of the XML to be imported, using both relative and absolute paths. Do not use the relative path.. To reference a file in the parent directory. Doing so creates dependencies on files external to the current application. Using absolute paths directly affects the location of file paths in different deployment environments. So a better approach is to resolve “$…” at run time according to the JVM system properties. Placeholder.

Groovy beans define the DSL

In addition to XML definitions, Spring can also be configured using Groovy beans.

Here is the definition of daos.groovy:

import com.flydean.daos.JpaAccountDao;
import com.flydean.daos.JpaItemDao;


beans{

    accountDao(JpaAccountDao){

    }

    itemDao(JpaItemDao){

    }
}
Copy the code

Quite simply, you define two beans.

Here is the definition of services.groovy:

import com.flydean.services.PetStoreService

beans {

    petStore(PetStoreService, accountDao){

        accountDao=accountDao
        itemDao=itemDao
    }
}
Copy the code

Using a container

ApplicationContext is a high-level factory interface that maintains the registration of different beans and their dependencies. An instance of the bean is obtained using the method T getBean(String Name, Class requiredType). ApplicationContext allows you to read bean definitions and access them, as shown in the following example:

        // create and configure beans
        ApplicationContext context = new ClassPathXmlApplicationContext("services.xml"."daos.xml");

        // retrieve configured instance
        PetStoreService service = context.getBean("petStore", PetStoreService.class);

        // use configured instance
        List<String> userList = service.getUsernameList();
Copy the code

With groovy bean configuration in mind, here’s how to use Groovy beans:

        // create and configure beans with groovy
        //daos.groovy must be written before services.groovy, otherwise the bean will not be found
        ApplicationContext context = new GenericGroovyApplicationContext("daos.groovy"."services.groovy");

        // retrieve configured instance
        PetStoreService service = context.getBean("petStore", PetStoreService.class);

        // use configured instance
        List<String> userList = service.getUsernameList();
Copy the code

When using groovy, note that daos.groovy must be written before services.groovy, otherwise the bean will not be found.

You can also use XmlBeanDefinitionReader and GenericApplicationContext combination of:

        GenericApplicationContext context = new GenericApplicationContext();
        //reader with xml
        new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml"."daos.xml");
Copy the code

You can also use GroovyBeanDefinitionReader to load the Groovy file, as shown below:

GenericApplicationContext context = new GenericApplicationContext();
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy"."daos.groovy");

Copy the code

The source code for this tutorial can be found in the Container module in Spring5-core-Workshop.

See flydean’s blog for more tutorials