1. 程式人生 > 其它 >Spring Doc - The IoC Container

Spring Doc - The IoC Container

1. The IoC Container

This chapter covers Spring’s Inversion of Control (IoC) container.

1.1. Introduction to the Spring IoC Container and Beans

IoC is also known as dependency injection (DI). In Spring, a bean is an object that is instantiated, assembled, and managed by a Spring IoC container.

1.2. Container Overview

The ApplicationContext interface represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans.

1.2.1. Configuration Metadata

Configuration metadata tell the Spring container to instantiate, configure, and assemble the objects in your application.

1.2.2. Instantiating a Container

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

1.2.3. Using the Container

// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);

1.3. Bean Overview

Beans are created with the configuration metadata that you supply to the container.

1.3.1. Naming Beans

Every bean has one or more identifiers. These identifiers must be unique within the container that hosts the bean.

1.3.2. Instantiating Beans

A bean definition is essentially a recipe for creating one or more objects.

1.4. Dependencies

A few objects that work together to present what the end-user sees as a coherent application.

1.4.1. Dependency Injection

Dependency injection (DI) is a process whereby objects define their dependencies.

1.4.2. Dependencies and Configuration in Detail

You can define bean properties and constructor arguments as references to other beans or as values defined inline.

1.4.3. Using depends-on

The depends-on attribute can explicitly force one or more beans to be initialized before the bean.

1.4.4. Lazy-initialized Beans

A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested.

1.4.5. Autowiring Collaborators

The Spring container can autowire relationships between collaborating beans.

1.4.6. Method Injection

When the beans lifecycles are different, you can get new bean instance from bean method.

1.5. Bean Scopes

You can control the scope of the objects created from a particular bean definition.

1.5.1. The Singleton Scope

Only one shared instance of a singleton bean is managed by the Spring container.

1.5.2. The Prototype Scope

Creation of a new bean instance every time a request for that specific bean.

1.5.3. Singleton Beans with Prototype-bean Dependencies

A new prototype bean is instantiated and then dependency-injected into the singleton bean.

1.5.4. Request, Session, Application, and WebSocket Scopes

They are available only if you use a web-aware Spring ApplicationContext implementation.

1.5.5. Custom Scopes

You can define your own scopes or even redefine existing scopes.

1.6. Customizing the Nature of a Bean

The Spring Framework provides a number of interfaces, you can use to customize the nature of a bean.

1.6.1. Lifecycle Callbacks

To interact with the bean lifecycle, you can implement the Spring InitializingBean and DisposableBean interfaces.
The @PostConstruct and @PreDestroy annotations are generally considered best practice in a modern Spring application.

1.6.2. ApplicationContextAware and BeanNameAware

Object instance that implements the ApplicationContextAware interface, the instance is provided with a reference to that ApplicationContext.
Object instance that implements the BeanNameAware interface, the instance is provided with a reference to the name defined.

1.6.3. Other Aware Interfaces

Spring offers a wide range of Aware callback interfaces that let beans indicate to the container that they require a certain infrastructure dependency.

1.7. Bean Definition Inheritance

A bean definition can contain a lot of configuration information, A child bean definition can inherits configuration data from a parent definition and can override some values or add others.

1.8. Container Extension Points

Spring IoC container can be extended by plugging in implementations of special integration interfaces.

1.8.1. Customizing Beans by Using a BeanPostProcessor

The BeanPostProcessor interface defines callback methods that you can implement to provide your own instantiation logic, dependency resolution logic, and so forth.

1.8.2. Customizing Configuration Metadata with a BeanFactoryPostProcessor

Spring IoC container lets a BeanFactoryPostProcessor read the configuration metadata and potentially change it before the container instantiates any beans other than BeanFactoryPostProcessor instances.

1.8.3. Customizing Instantiation Logic with a FactoryBean

The FactoryBean interface is a point of pluggability into the Spring IoC container’s instantiation logic.

1.9. Annotation-based Container Configuration

Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

1.9.1. @Required

Affected bean property must be populated at configuration time.

1.9.2. @Autowired

Spring to provide all beans by adding the @Autowired annotation to a field.

1.9.3. Annotation-based Autowiring with @Primary

Because autowiring by type may lead to multiple candidates. One way to accomplish this is with Spring’s @Primary annotation.

1.9.4. Annotation-based Autowiring with @Qualifier

You can associate qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument.

1.9.5. Using Generics as Autowiring Qualifiers

In addition to the @Qualifier annotation, you can use Java generic types as an implicit form of qualification.

1.9.6. Using CustomAutowireConfigurer

CustomAutowireConfigurer lets you register your own custom qualifier annotation types.

1.9.7. @Resource

Spring also supports injection by using the JSR-250 @Resource annotation.

1.9.8. @Value

@Value is typically used to inject externalized properties.

1.9.9. @PostConstruct and @PreDestroy

These annotations offers an alternative to the lifecycle callback mechanism.

1.10. Classpath Scanning and Managed Components

This section describes an option for implicitly detecting the candidate components by scanning the classpath.

1.10.1. @Component and Further Stereotype Annotations

Spring provides further stereotype annotations: @Repository, @Service, and @Controller are specializations of @Component.

1.10.2. Using Meta-annotations and Composed Annotations

A meta-annotation is an annotation that can be applied to another annotation. For example, the @Service annotation mentioned earlier is meta-annotated with @Component.

1.10.3. Automatically Detecting Classes and Registering Bean Definitions

Spring can automatically detect stereotyped classes and register corresponding BeanDefinition instances with the ApplicationContext.

1.10.4. Using Filters to Customize Scanning

However, you can modify and extend the detected candidate components by applying custom filters.

1.10.5. Defining Bean Metadata within Components

You can do this with the same @Bean annotation used to define bean metadata within @Configuration annotated classes.

1.10.6. Naming Autodetected Components

Spring stereotype annotation that contains a name value thereby provides that name to the corresponding bean definition.

1.10.7. Providing a Scope for Autodetected Components

Sometimes you need a different scope that can be specified by the @Scope annotation.

1.10.8. Providing Qualifier Metadata with Annotations

When relying upon classpath scanning for auto-detection of components, you can provide the qualifier metadata with type-level annotations on the candidate class.

1.10.9. Generating an Index of Candidate Components

To generate the index, add an additional dependency to each module that contains components that are targets for component scan directives.

1.11. Using JSR 330 Standard Annotations

Those annotations are scanned in the same way as the Spring annotations.

1.11.1. Dependency Injection with @Inject and @Named

Instead of @Autowired, you can use @Inject.If you would like to use a qualified name for the dependency that should be injected, you should use the @Named annotation.

1.11.2. @Named and @ManagedBean: Standard Equivalents to the @Component Annotation

Instead of @Component, you can use @Named or ManagedBean.

1.11.3. Limitations of JSR-330 Standard Annotations

When you work with standard annotations, you should know that some significant features are not available.

1.12. Java-based Container Configuration

This section covers how to use annotations in your Java code to configure the Spring container.

1.12.1. Basic Concepts: @Bean and @Configuration

The @Bean annotation is used to indicate that a method instantiates, configures, and initializes a new object to be managed by the Spring IoC container. Annotating a class with @Configuration indicates that its primary purpose is as a source of bean definitions.

1.12.2. Instantiating the Spring Container by Using AnnotationConfigApplicationContext

The following sections document Spring’s AnnotationConfigApplicationContext.

1.12.3. Using the @Bean Annotation

@Bean is a method-level annotation and a direct analog of the XML element.

1.12.4. Using the @Configuration annotation

@Configuration is a class-level annotation indicating that an object is a source of bean definitions.

1.12.5. Composing Java-based Configurations

Spring’s Java-based configuration feature lets you compose annotations, which can reduce the complexity of your configuration.