Spring Core Technologies

发布时间 2023-03-27 13:53:56作者: zexuan

Core Technologies

1. The IoC Container

1.1 Introduction to the Spring IoC Container and Beans

  • Service Locator pattern
  • The BeanFactory interface provides an advanced configuration mechanism capable of managing any type of object.
    • ApplicationContext is a sub-interface of BeanFactory. It adds:
      • Easier integration with Spring’s AOP features
      • Message resource handling (for use in internationalization)
      • Event publication
      • Application-layer specific contexts such as the WebApplicationContext for use in web applications.

1.2. Container Overview

  • The org.springframework.context.ApplicationContext interface represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans.
  • The configuration metadata represented in:
    • XML
    • Java annotations
    • Java code
  • ClassPathXmlApplicationContext and FileSystemXmlApplicationContext is implementations of the ApplicationContext which is commonly used by stand-alone applications

1.2.1. Configuration Metadata

  • The Spring IoC container itself is totally decoupled from the format in which this configuration metadata is actually written.

  • These days, many developers choose Java-based configuration for their Spring applications.

  • note the differences?:

    • Annotation-based configuration: define beans using annotation-based configuration metadata.
    • Java-based configuration: define beans external to your application classes by using Java rather than XML files. To use these features, see the @Configuration, @Bean, @Import, and @DependsOn annotations.
  • basic structure of 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>
    

1.2.2. Instantiating a Container

  • The location path or paths supplied to an ApplicationContext constructor are resource strings that let the container load configuration metadata from a variety of external resources, such as the local file system, the Java CLASSPATH, and so on.

    ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
    
  • In particular, Resource paths are used to construct applications contexts, as described in Application Contexts and Resource Paths.