Basic concepts of beans in spring

Source: Internet
Author: User

From the front we know that spring is actually a large factory, and the bean in the spring container is the product of that factory. For spring containers to produce those products, it depends on the configuration file.

For us, what we do with the spring framework is two things: developing beans, configuring beans. For spring mining, what it does is to create a bean instance from the configuration file and invoke the Bean instance's method to complete the dependency injection.

First, the bean definition

The <beans.../> element is the root element of the spring configuration file,,<bean.../>, Element division <beans. The child element of the/> element,<beans.../> element can contain multiple <bean.../> child elements, each of the <bean.../> elements can define a bean instance, Each bean typically needs to specify two properties when it corresponds to a Java instance definition bean in the spring container.

Id: Determines the unique identifier of the bean, which is accomplished by the container's dependency on bean management, access, and the bean. The bean's ID attribute is unique within the spring container.

Class: Specifies the specific implementation class for the bean. Note that the interface cannot be made here. Typically, Spring creates an instance of the bean directly using the new keyword, so the class name of the Bean implementation class must be provided here.

Here's a simple configuration that defines a bean

<?xml version="1.0"encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://www.springframework.org/schema/beans"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-3.0.xsd "><!--Define the first instance of the bean: bean1--<bean id="Bean1" class="com. Bean1"/> <!--Define a second bean instance: bean2---<bean id="bean2" class="com. Bean2"/> </bean>

The spring container centrally manages the instantiation of the bean, and the bean instance can be obtained through the beanfactory Getbean (Stringbeanid) method. Beanfactory is a factory where the program only needs to get a beanfactory reference to get a reference to all instances of the spring container management. The program does not need to be coupled with the implementation process of the specific instance. In most Java EE applications, when the application is started, the spring container is created automatically, and the components are coupled directly in a dependency injection, even without having to actively access the spring container itself.

When we are in the config file through <bean id= "xxxx" class= "xx. Xxclass "/> Method when configuring a bean, this requires that the bean implementation class must have an parameterless constructor. So the bottom of spring is equivalent to calling the following code:

new xx. Xxclass ()  

If you create a bean in a configuration file by constructing injection:

<?xml version="1.0"encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://www.springframework.org/schema/beans"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-3.0.xsd "><bean id="Bean1" class="com. Bean1"> <constructor-arg value="Chenssy"/> <constructor-arg value="35-354"/> </bean> </beans>

Then spring is equivalent to calling the following code:

new com. Test ("chenssy","35-354");  

In addition to specifying an ID property for the <bean.../> element, you can specify the Name property for the <bean.../> element to specify an alias for the Bean instance. If you need to specify more than one alias for a bean instance, you can use commas, colons, or spaces in the Name property to separate multiple aliases, followed by any alias to access the Bean instance. However, in some special cases, the program cannot specify all aliases when defining the bean, but instead assigns an alias to an already existing bean instance elsewhere, it can be done with the <alias.../> element, which has the following two attributes:

Name: This property specifies the identity name of a bean instance, indicating that the bean will be assigned an alias.

Alias: Specifies an alias.

Such as:

<alias name= "Bean1" alias= "name1"/>  <alias name= "bean2" alias= "name2"/>  

By default, when spring creates a ApplicationContext container, Spring automatically pre-initializes all of the singleton instances in the container, and if we want the spring container to pre-initialize a singleton Bean, you can The <bean.../> element adds the Lazy-init property, which is used to specify the pre-initialization of the bean instance, and if set to true, spring does not pre-initialize the bean instance.

class= "com. Person "lazy-init="true"/>  

  

The scope of a bean in a container when you create a bean instance from a spring container, you can not only instantiate the bean instance, but also specify a specific scope for the bean.

Spring supports 5 scopes:

Singleton: Singleton mode. In the entire SPRINGIOC container, the bean defined with Singleton will have only one instance.

Prototype: Prototype mode. Each time a prototype-defined bean is obtained through the container's Getbean method, a new bean instance is generated.

Request: For each HTTP request, the bean defined with the request will produce a new instance, that is, each HTTP request will produce a different bean instance. Of course, this scope is only really effective when you use spring in a web app.

Session: For each httpsession, the bean defined with the session will produce a new instance, that is, each HTTP session will produce a different bean instance. As with HTTP, only the Web app will work.

Global session: Each global httpsession corresponds to a bean instance. Valid only in the context of the portlet.

Compare common Singleton and prototype. If a bean instance is set to Singleton, the same instance will be obtained each time the bean is requested. The container is responsible for tracking the state of the bean instance and is responsible for maintaining the life cycle behavior of the bean instance. If a bean instance is set to prototype, then each request for the DI's bean,spring creates a new bean instance to return to the program, in which case the spring container simply creates the bean instance using the New keyword, and once it is created successfully, The container will no longer track the instance, nor will it maintain the state of the bean instance.

If we do not specify the scope of the bean, Spring uses the singleton scope by default.

Java requires a memory request when it creates a Java instance. When you destroy an instance, you need to complete the garbage collection. These efforts can lead to increased overhead. Therefore, the cost of creating and destroying prototype-scoped beans will be large. Once the bean instance of the singleton scope is successfully created, it can be reused. Therefore, try to avoid setting the scope of the bean to prototype, unless necessary.

Setting the scope of the bean is specified by the scope property. Can accept Singleton, prototype, request, session, global session 5 values.

<?xml version="1.0"encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://www.springframework.org/schema/beans"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-3.0.xsd "><!--Configure a singleton bean instance: Default--<bean id="Bean1" class="com. Bean1"/> <!--Configuring a prototype bean instance--<bean id="bean2" class="com. Bean2"Scope="prototype"/> </beans>

The above configuration, the scope property is not specified for Bean1, and Singleton is used by default, and Bean2 specifies a prototype.

Test code:

 Public classSpringtest { Public Static voidMain (string[] args) {ApplicationContext ctx=NewClasspathxmlapplicationcontext ("Bean.xml"); //determine if the bean instances of the singleton scope are equal for two requestsSystem. out. println (Ctx.getbean ("Bean1") ==ctx.getbean ("Bean1")); //determine if the bean instances of the prototype scope are equal for two requestsSystem. out. println (Ctx.getbean ("bean2") ==ctx.getbean ("bean2")); }    }  

The program runs the following results

True

False

As can be seen from the running results above: for singleton-scoped beans, each time the bean of the ID is requested, the same bean instance is returned, but prototype returns a new bean instance, and each request returns a different instance of the bean.

For the request scope, look at the following Bean instance definition:

class= "Com.app.LoginAction" scope= "Request"/>  

For each HTTP request, the spring container creates a completely new instance of the Loginaction bean based on the login bean definition, and the loginaction bean instance is valid only within the current HTTP request.

Same for session scopes. Only the effective range is different.

The request and session scopes are only valid in Web apps and must be added to the Web app for additional configuration to take effect. In order for request and session two scopes to take effect, the HTTP request object must be bound to the service thread provided by the request, which allows the bean instance with request and session functions to be accessed in the subsequent call chain.

So we can use two configurations: the listener configuration or the filter configuration in Web. Xml.

Listener configuration:

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

Filter configuration

<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>  

Once you add one of the two configurations in Web. XML, the program can use the request or session scope in the spring configuration file. As follows:

<?xml version="1.0"encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://www.springframework.org/schema/beans"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans-3.0.xsd "><!--specify to use the request scope--<bean id="P" class="Com.app.Person"Scope="Request"/> </beans>

The above configuration file configures a bean that implements the class person, specifying its scope as request. This causes the spring container to generate an instance of the person for each HTTP request, which is also logged off when the request response ends.

Basic concepts of beans in spring

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.