Spring Learning Path (iii)

Source: Internet
Author: User

Preface: For developers using the spring framework, there are two main things we do: ① develop Bean;② configuration beans, and what spring does for us is to create a bean instance from the configuration file and invoke the method of the bean instance to complete the dependency injection. The spring container can be understood as a large factory, the bean is the product of the factory, the factory (Spirng container) can produce what kind of products (beans), completely depends on our configuration in the configuration file. So today we're going to talk about the bean story ...

Scope of Bean in container

Singleton In the entire Spring IoC container, the bean defined with Singleton will have only one instance
Prototype Prototype mode, which generates a new bean instance each time a prototype-defined bean is obtained through the container's Getbean method
Request For each HTTP request, the bean defined with the request will produce a new instance, each time the HTTP request will produce a different bean instance, which is only valid in the spring ApplicationContext scenario given to the Web
Session For each HTTP session, the bean defined with the session will produce a new instance that is only valid in the spring ApplicationContext scenario that gives the Web
Global session Each global HTTP session corresponds to a bean instance that is valid only in the spring ApplicationContext scenario that gives the Web

More commonly used is the singleton and prototype two scopes, for the singleton scope, each request for the bean will get the same instance, the spring container is responsible for tracking the state of the monitoring Bean instance, responsible for maintaining the life cycle behavior of the bean instance, If a bean is set to prototype scope, the program will create a new bean instance each time the Bean,spring requests that ID, and then return it to the program, in which case the spring container simply creates the bean instance using the New keyword, and once it is successfully created, The container spring no longer takes responsibility for the bean's life cycle, nor does it maintain the state of the bean instance.

If you do not specify a scope for the bean, Spring uses the singleton scope by default. When Java is a common Java instance, a memory request is required and the instance is destroyed, and the garbage collection needs to be completed, which can lead to increased overhead. Therefore, the creation of prototype-scoped beans is costly to destroy. The bean instance of the singleton scope can be reused once it is created, so avoid setting the bean scope to prototype unless necessary.

If you want to use a Request,session,global session-scoped Bean, you need to do a small amount of initial configuration before you configure the bean ( banding the HTTP request to the service-provider thread. This allows the bean instance with the request and session scope to be accessed in the subsequent call chain, without setting if the general scope (Singleton,prototype) is only configured. If your web App uses spring MVC directly as the MVC framework, which uses Springdispatcherservlet or dispatcherporlet to intercept all user requests, you don't need to set them up because Dispatcherservlet And Dispatcherporlet have dealt with all and request-related amounts of status processing.

When using a Web container other than the specifications of the servlet 2.4 and above in spring ' s dispatcherservlet, you need to add the following configuration in ' Web. Xml ':

< Listener >        < Listener-class >org.springframework.web.context.request.RequestContextListener</listener-class  >    </listener>

If you are using an early version of the Web container, the container does not support the listener specification, so you cannot use the above configuration, only the filter configuration mode, the configuration code is as follows:

<Filter>        <Filter-name>Requestcontextfilter</Filter-name>        <Filter-class>Org.springframework.web.filter.RequestContextFilter</Filter-class></Filter><filter-mapping>        <Filter-name>Requestcontextfilter</Filter-name>        <Url-pattern>/*</Url-pattern></filter-mapping>

The life cycle of a bean in a container

Spring can manage the life cycle of the singleton scope Bean , and spring can know exactly when the singleton domain Bean was created, when it was initialized, and when the container was ready to destroy the bean instance. Because, for singleton-scoped beans, each request from the client returns the same bean instance, the client code does not control the bean's destruction, and its life cycle is in the hands of spring. As a result, the container can manage the behavior of the instantiation (the application of some resources) and before the destruction (the recycling of some resources). There are two opportunities to manage the life cycle behavior of a bean: before it is injected, the instance is destroyed, and the specific management method is as follows

Spring provides two ways to perform a specific behavior after the bean full property setting succeeds

Using the Init-method property (code pollution is small)

Write a method in the class that specifies that the method is automatically executed after the dependency setting is complete in the property.

Implement Initializingbean interface (high coupling)

Specific implementation of writing Afterpropertiesset () methods

Similarly, if you execute a specific method before the bean is destroyed, you only need to implement the Disposablebean interface using the Destroy-method property ② (Implement the Destroy () method) ①

The bean,spring container for the prototype scope is responsible only for the creation of the bean, and when the container creation instance is complete, the bean is completely given to client code management, and the container is no longer responsible for its lifecycle. Each time a client requests a prototype-scoped bean, the spring container produces a completely new bean instance to the client (prototype is so wayward), and the spring container does not know how many instances it has created. It is even more impossible to know when these instances will be destroyed.

Spring's Bean and JavaBean comparison

      1. Specification: The spring container does not have special requirements for beans, and does not follow some specifications like JavaBean (providing the appropriate setter and getter method for each property), but it is important to provide setter methods for the bean that sets the value injection.
      2. Role: The Bean in Spring is a Java instance, Java component, it is almost all-encompassing, any application components are called beans, and traditional Java application JavaBean usually as a DTO (data transfer object), to encapsulate the value object, passing data between the layers.
      3. Life cycle: Traditional JavaBean is passed as a value object, does not accept any container to manage its lifecycle, and spring's bean has spring to manage its life cycle behavior.

The difference between Spring's bean inheritance and Java inheritance

      1. Spring neutron beans and parent beans can be of different types, while inherited subclasses in Java are just a special type of parent class.
      2. The inheritance of Bean in spring is the relationship between the instances, which mainly manifests as the continuation of the parameter values, and the Java end inheritance is the relationship between the classes, which mainly manifests as the property and the continuation of the method.
      3. Spring neutron beans cannot be used by parent beans and are not polymorphic, and subclass instances in Java can be used entirely as instances of the parent class

How Bean instances are created and dependent configurations

In most cases, the beanfactory directly invokes the constructor with the new keyword to create the bean instance, while the class attribute specifies the implementation class for the Bean instance. But this is not the only way to instantiate a bean.

There are typically three ways to create a bean:

      1. Invoking the constructor to create a bean instance
      2. Calling a static factory method to create a bean
      3. Invoking an instance factory method to create a bean
      • Invoking the constructor to create a bean instance

Invoking the constructor to create a bean instance is the most common case, and beanfactory will use the default constructor to create the bean instance, which is the default instance, and spring performs the default initialization for all properties of the bean instance, that is, the values of all the basic types are initialized to 0 or false, The reference type is initialized to null, and then Beanfactory determines the dependency based on the configuration file, instantiates the dependent bean instance first, then injects a dependency on the bean, and finally returns a full bean instance to the program, all the attributes that the bean instantiates, Initialization has been done by the spring container.

      • To create a bean using the static factory method

When you create a bean instance using the static factory method, the class property must also be specified, but at this point the Class property is not the implementation class for the specified bean instance, but the static factory class , and spring needs to create the bean instance based on the factory method of the plant class, in addition to You also need to use the Factory-method property to specify the static factory method name , and spring calls the static factory method (which may contain a set of parameters, if required, using <constructor-arg ... /> element passed in) returns a Bean instance, and after the bean instance is obtained, the processing steps behind spring are exactly the same as creating the bean instance in the normal way.

When you use the static factory method to create a bean instance, spring parses the configuration file and, based on the information specified by the configuration file, invokes the static factory method of the static factory class by reflection, using the lake value of the static factory method as the bean instance. In this process, spring is no longer responsible for creating the bean instance, and the creation of the bean instance is created by the user-supplied static factory class. But the spring container can still manage the dependency, life cycle, of the bean instance.

      • Using Instance factory methods

The instance factory method differs from the static factory method: Calling the static Factory method requires only the factory class, and invoking the instance factory method must use the factory instance. When using the instance factory method, configure the <bean of the bean instance. The/> element does not require a class attribute because the spring container is no longer directly instantiating the bean,spring container merely invoking the factory method of the instance factory, which is responsible for creating the bean instance. When you create a bean using the instance factory method, you need to <bean. The/> element specifies the following two properties: Factory-bean: The value of this property is the Id.factory-method of the factory Bean: This property specifies the factory method of the instance factory. Similar to the static factory method, if you need to pass in parameters when calling the factory method, use <constructor-arg ... The/> element determines the parameter value.

Static factory methods create instances and plant methods to create instances of similarities and differences :

Invoking the instance factory method to create the bean, the instance factory must be configured as a bean instance. Instead of configuring the factory bean, the static factory method creates the bean.

Call the instance factory method to create the bean, you must use the Factory-bean property to determine the factory bean. While the static factory method creates the bean, it uses the class element to determine the static factory class.

Requires Factory-method to specify the factory method that produces the bean instance accordingly.

The factory method requires parameters that can be specified using the <constructor-art.../> element.

Spring Learning Path (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.