Spring core technology (1)

Connect papers: the Spring Framework Overview

version 5.1.8.RELEASE

This part of the reference documentation covers the Spring Framework all absolutely indispensable technology.

One of the most important is the Spring Framework's Inversion of Control (IoC) container. After describing IoC container Spring Framework, followed by a comprehensive introduction Spring aspect-oriented programming (AOP) technology. Spring Framework has its own AOP framework, it is easy to understand in concept, and successfully locate the sweet spot 80% of enterprise Java programming AOP needs.

Spring provides AspectJ (currently most feature-rich, enterprise Java world is the most mature AOP implementation) integration.

1. IoC container

This chapter describes Spring Inversion of Control (IoC) container.

1.1 Spring IoC container and Bean Profile

This chapter describes the implementation principle Spring Framework Inversion of Control (IoC) is. IoC also called dependency injection (DI). Through this mechanism, the object can be parameterized by the constructor parameters and factory methods on instance attributes set by a building or factory method returns to define their dependencies (i.e. they use other objects). The container is then injected these dependencies when creating the bean. This process is reversed from the fundamental mechanisms Bean itself by directly calling the constructor or service positioning mode to control their instantiation or location-dependent mode, therefore, called inversion of control.

org.springframework.beansAnd the org.springframework.contextpackage is based IoC container Spring Framework. BeanFactoryInterface provides advanced configuration mechanism capable of managing any type of object. ApplicationContextIt is a subclass of BeanFactory. It added contents include:

  • Easier integration with Spring's AOP functionality
  • Message resource handling (for international)
  • Event Publishing
  • Particular context application layer, e.g. WebApplicationContext used in Web application

In short, BeanFactoryit provides the configuration framework and basic functionality, ApplicationContextadd more features for enterprise level. ApplicationContextIt is BeanFactorya full superset, in this chapter only describes the Spring IoC container. About using BeanFactoryinstead ApplicationContextfurther information, please refer to BeanFactory .

In Spring, constitute an application framework managed by the Spring IoC container object called beans. It is an instance of the bean, assembly or managed by the Spring IoC container object. In addition, bean is just one of the many application objects. Bean dependencies between them is reflected in the configuration used in the metadata container.

1.2 Overview of the container

org.springframework.context.ApplicationContextInterface represents Spring IoC container, instantiates, the configuration and assembly bean. Container for information about configuration metadata need to be instantiated, the configuration and assembly of the object by reading the instructions. Configuration metadata to XML, Java annotations or Java code, said it can be represented by a wealth of dependencies between objects and objects that make up the application.

Spring offers a variety of ApplicationContextinterfaces. In the traditional stand-alone applications, often create a ClassPathXmlApplicationContextor FileSystemXmlApplicationContextinstance. Although XML configuration metadata is defined traditional format, but you can also provide a small amount of XML configuration statement container after enable support for other formats using Java metadata annotations or code as the metadata format.

In most application scenarios, no explicit use of the container code to instantiate instances Spring IoC. For example, in a Web application scenarios, the application web.xml file in about an 8-line web template XML description is sufficient (See Web applications quickly instantiated ApplicationContext ). If you use the Spring Tool Suite (an Eclipse-based development environment), just a few clicks of the mouse or pressing a few keystrokes you can easily create the template configuration.

The figure is high-level view Spring works. Application class configuration metadata combining the ApplicationContextfollowing is created and initialized, and has a fully configured system, or executable applications.

images/container-magic.png

1.2.1 configuration metadata

Shown, Spring IoC container as metadata a number of configurations in FIG. The configuration metadata describes how to instantiate Spring container in the application, the configuration and assembly of objects.

Traditional configuration metadata using a simple and intuitive XML format, most of this chapter is using XML to express the Spring IoC container of key concepts and features.

XML is not the only configuration metadata format. Spring IoC container and the actual writing of configuration metadata format completely decoupled. Currently, many developers choose their Spring applications Java-based configuration .

Metadata about using other forms in the Spring container, see:

  • Annotation-based configuration : Spring 2.5 introduces support for annotation-based configuration metadata.
  • Java-based configuration : Starting from Spring 3.0, Spring JavaConfig many of the features provided by the project to be part of the core Spring Framework. Therefore, you can use Java instead of XML file to define an external application class bean. To use these new features, see @Configuration, @Bean, @Import, and @DependsOnannotations.

Spring configuration information by at least one (typically more than one) must be managed bean defined by the containers. XML-based configuration metadata of these bean configured as top-level elements <beans/>within the <bean/>element. Typically using a Java-based configuration @Configurationusing annotated class @Beanannotated method.

These bean definition constitutes the actual application object. We usually define the service layer objects, Data Access Objects (DAO), the presentation layer objects (such as Struts Action instances), infrastructure objects (such as Hibernate SessionFactories, JMS Queues, etc.). Generally does not configure fine-grained domain objects in the container, because usually the responsibility of the DAO and business logic to create and load the domain objects. However, you can use Spring to configure AspectJ integration of non-target IoC container to create. See using Spring and AspectJ to dependency inject domain objects .

The following example shows the basic structure of the XML-based configuration metadata:

<?xml version="1.0" encoding="UTF-8"?>
<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="..." class="...">①②
        <!-- collaborators and configuration for this bean go here -->
    </bean>

    <bean id="..." class="...">
        <!-- collaborators and configuration for this bean go here -->
    </bean>

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

</beans>

① id attribute is a string that identifies an individual bean definition

② class properties using the full name of the class definition of the type of bean

id attribute value represents the collaboration object. In this example, the XML for the referenced object is not included in the collaboration. For more information, please refer to the dependent .

1.2.2 Examples of the container

ApplicationContext constructor provided to position the path is a string resource, which allows the container loading configuration metadata from various external resources, such as a local file system, Java environment variables.

ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");

After learning of the Spring IoC container, you may want to know about the Spring 资源abstraction (see 资源description) for more information, especially Resourcethe path for building application context (refer to the application context and resource path ), which provides a convenient mechanism for defining the position of the statement is read from the URI InputStream. .

The following example shows the service layer object configuration files (services.xml):

<?xml version="1.0" encoding="UTF-8"?>
<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="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

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

</beans>

The following example shows the Data Access Object files (daos.xml):

<?xml version="1.0" encoding="UTF-8"?>
<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="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

    <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
        <!-- additional collaborators and configuration for this bean go here -->
    </bean>

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

</beans>

In the preceding example, the service layer of PetStoreServiceImplclasses and two data access objects JpaAccountDao, and JpaItemDao(based on the object-relational mapping JPA standard) composition. propertyElement nameattributes is the name of JavaBean property, refattribute points to another bean defined name. Element idand refthis link between the expression of dependencies between collaborators. For more information on configuring object dependencies, see dependencies .

Write the XML-based configuration metadata

Typically, each individual XML configuration files or modules corresponding to the logical layer architecture, allowing multiple XML bean definition file take effect will be very useful.

As described above in an application context constructor may be used a plurality of Resource positions, it can be loaded from the XML definitions bean fragments. Alternatively, you can use one or more <import/>elements loaded bean definitions from another file. The following example shows how to do this:

<beans>
    <import resource="services.xml"/>
    <import resource="resources/messageSource.xml"/>
    <import resource="/resources/themeSource.xml"/>

    <bean id="bean1" class="..."/>
    <bean id="bean2" class="..."/>
</beans>

In the preceding example, the external load Bean definitions from the three files, namely services.xml, messageSource.xml and themeSource.xml. For the definition files for import is, all paths are relative to the path, and therefore must import the file services.xml performed in the same directory or environment variables, and themeSource.xml messageSource.xml, must be located below the import file resources directory path in. As you can see, in front of the slash is ignored. Given the relative paths are provided, so it is best not to use slashes. These documents include the right to import the contents of XML Bean Spring Schema definitions, including the city, including the top-level element <beans/>.

Although you can use a relative path, "../" references the parent directory, but such use is not recommended, because doing so will make the current application dependent files outside of the program. Very not recommended classpath:URL (for example, classpath: ../ services.xml) references, because parsing process will select the "recent" in the root directory of the runtime environment variables, and then look for its parent directory. Environment variable configuration changes may cause the directory incorrectly selected.

Can use the full resources path relative position of substitution, for example, file: C: /config/services.xml or classpath: /config/services.xml. However, it should be noted that the configuration of the application will be coupled with a specific absolute path. Usually best to keep the absolute path for these indirect contact, for example by running the "$ {...}" placeholder alternative JVM system property.

Import namespace itself provides the function of an instruction. Spring provides a series of XML namespace provides additional configuration features in addition to the ordinary bean definitions, such as context and util namespace.

Groovy Bean definition of DSL

As another example of the outer configuration of the metadata, the definition of the bean can also be represented in the Spring of the DSL Groovy Bean definitions, as Grails framework. Such a configuration is usually located ".groovy" file, the structure of the following example:

beans {
    dataSource(BasicDataSource) {
        driverClassName = "org.hsqldb.jdbcDriver"
        url = "jdbc:hsqldb:mem:grailsDB"
        username = "sa"
        password = ""
        settings = [mynew:"setting"]
    }
    sessionFactory(SessionFactory) {
        dataSource = dataSource
    }
    myService(MyService) {
        nestedBean = { AnotherBean bean ->
            dataSource = dataSource
        }
    }
}

This configuration style is largely identical to the XML bean definition, also supports Spring XML configuration namespaces. It also allows importBeansto import XML bean definition files direct instruction.

1.2.3 Use containers

ApplicationContextIs an advanced factory interface, is responsible for maintaining different bean and its dependencies registered items. By using T getBean(String name, Class<T> requiredType)examples of Bean method can be obtained.

By ApplicationContextread bean define and access them, 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();

When using Groovy configuration, the initialization program looks very similar. Except that the context of Groovy implementation class support (also supports XML bean definition). The following example shows the Groovy configuration:

ApplicationContext context = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");

Most flexible use is GenericApplicationContextto delegate the reader combination, for example, using the XML file XmlBeanDefinitionReader, as shown in the following example:

GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();

Groovy may also be used for file use GroovyBeanDefinitionReader, as shown in the following example:

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

You can be the same ApplicationContextusing such mixed commission reader reads bean definitions from different sources configuration.

You can use the getBeanmethod to get Bean instance. ApplicationContextInterface There are other ways to get bean, but ideally your application should not use them. In fact, your application code does not should call getBean () method, it should not depend on Spring API. For example, Spring integrated framework for various Web Web frame assembly (e.g., the controller and the JSF managed bean) provides dependency injection to a particular dependence of the bean, for example, by automatic assembly annotation metadata declaration.

Guess you like

Origin www.cnblogs.com/aotian/p/11087068.html