Use of the Spring Series Bean

Source: Internet
Author: User

First, the bean definition

<bean id= "Userdao" class= "Com.dev.spring.simple.MemoryUserDao"/>
This is one of the simplest Bean definitions. It is similar to calling a statement:
Memoryuserdao Userdao = new Memoryuserdao ().

The id attribute must be a valid XML ID, which means that it must be unique throughout the XML document. It is a "lifetime code" for a Bean. You can also use the Name property to define one or more individual names for the Bean (separate multiple aliases with commas or spaces). The Name property allows any illegal XML letter to appear. For example:

<bean id= "Userdao" Name= "Userdao*_1, userdao*_2" class= "Com.dev.spring.simple.MemoryUserDao"/>.

The class attribute defines the fully qualified class name (package name + class name) of the Bean. Spring can manage almost all Java classes. In general, this Java class will have a default constructor that sets the dependent properties with the set method.

The Bean element is out of the two attributes above, and there are many other properties. The description is as follows:

<bean    id= "Beanid" (1)    name= "Beanname" (2)    class= "Beanclass" (3)    parent= "Parentbean" (4)    Abstract= "true | False "(5)    singleton=" true | false "(6)    lazy-init=" true | false | default "(7)    autowire=" No | byname | bytype | c Onstructor | AutoDetect | Default "(8)    Dependency-check =" none | Objects | Simple | All | Default "(9)    depends-on=" Dependsonbean "(Ten)    init-method=" method "(one)    destroy-method=" method "(12)    factory-method= "Method" (factory-bean=)    "Bean" > (+) </bean>

(1) The unique identification name of the Id:bean. It must be a valid XML ID that is unique throughout the XML document.

(2) Name: Used to create one or more individual names for the ID. It can be any letter of the match. Multiple aliases are separated by commas or spaces.

(3) Class: Used to define the fully qualified name of the class (package name + class name). Only the subclass Bean does not have to define this property.

(4) Parent: The subclass Bean defines the parent class bean to which it refers. The preceding class attribute is invalidated. The subclass Bean inherits all the properties of the parent class bean, and the subclass Bean can override the parent class Bean's properties. Note: The subclass Bean and the parent class bean are the same Java class.

(5) Abstract (default = "false"): used to define whether the bean is an abstract bean. It means that the bean will not be instantiated, typically for the parent class Bean, because the parent class bean is primarily intended for use by the subclass Bean.

(6) Singleton (default = "true"): Defines whether the Bean is singleton (singleton). If set to "true", only one instance of this Bean is maintained within the scope of beanfactory. If set to "Flase", the Bean will be Prototype (prototype) state, Beanfactory will create a new bean instance for each bean request.

(7) Lazy-init (default): Used to define whether the Bean implements lazy initialization. If true, it initializes all Singleton beans at beanfactory startup. Conversely, if it is "false", it will only start creating the Singleton bean when the bean is requested.

(8) Autowire (auto-assemble, default = "Defaults"): It defines how the Bean is automatically loaded.
"No": no automatic assembly function is used.
"ByName": Automatic assembly via the Bean's property name.
"Bytype": Automatic assembly by type of Bean.
"Constructor": similar to Bytype, but it is an automatic assembly of the parameters used to construct the function.
"AutoDetect": The Bean class's introspection mechanism (introspection) determines whether to use "constructor" or "Bytype".

(9) Dependency-check (dependency check, default = "Defaults"): It is used to ensure that the Bean component is satisfied with the dependency relationship described by JavaBean. It is especially useful when used with automatic assembly features.
None: Dependency checking is not performed.
Objects: Only check for dependencies between objects.
Simple: Check only for primitive type and String type dependencies
All: Checks for all types of dependencies. It includes the front objects and simple.

Depends-on (Dependent object): The object that this bean relies on during initialization, which is created before the bean is initialized.

Init-method: The initialization method used to define the bean, which is called after the Bean is assembled. It must be a non-parametric method.

Destroy-method: Used to define the Bean's destruction method, which is called when the beanfactory is closed. Similarly, it must also be a parameterless method. It can only be applied to singleton beans.

Factory-method: Defines the factory method that creates the Bean object. It is used for the following "Factory-bean", which means that the bean is created through a factory method. At this point, the "class" attribute is invalidated.

Factory-bean: Defines the factory class that created the Bean object. If "Factory-bean" is used, the "class" attribute is invalidated.

Ii. three ways to instantiate beans

1. Instantiating a bean using a constructor

This is the simplest way, the Spring IOC container can use the default null constructor and can also create beans in two ways, using the parametric constructor.
Defined with an empty constructor, the class property specifies that the classes must have an empty constructor. Defined using the parametric constructor, you can use the < Constructor-arg > tag to specify the constructor parameter value, where index represents the position, value represents a constant value, or a reference, and the specified reference uses ref to refer to another bean definition. Details will be presented in the rear. Let's look at an example:

(1) Define an interface

Package Com.spring.service;public interface Iuserservice {public    void Show ();

(2) The implementation class, which has an empty constructor and a parametric constructor:

Package Com.spring.service.impl;import Com.spring.service.iuserservice;public class Userserviceimpl implements iuserservice{        private String message;        Public Userserviceimpl () {        this.message= "Lixiaoxi";    }        Public Userserviceimpl (String message) {        this.message=message;    }        public void Show () {        System.out.println ("Hello," +message);}    }

(3) Configure the bean definition in the configuration file (Applicationcontext1.xml) as follows:

<!--using the default constructor--><bean id= "Bean1" class= "Com.spring.service.impl.UserServiceImpl" >  
</bean> <!--using the parametric constructor--><bean id= "Bean2" class= "Com.spring.service.impl.UserServiceImpl" > <!--specifying constructor parameters-- <constructor-arg index= "0" value= "Zhangsan"/></bean>

(4) test method:

/** * Using the constructor to instantiate the bean */@Testpublic void Testcreatebeanbyconstructor () {    //Read the configuration file    ApplicationContext ctx=new Classpathxmlapplicationcontext ("Applicationcontext1.xml");    Gets the instance of the bean    Iuserservice bean1= (iuserservice) Ctx.getbean ("Bean1");    Call Method    bean1.show ();        Iuserservice bean2= (Iuserservice) Ctx.getbean ("bean2");    Bean2.show ();}

2. Instantiating a bean using the static factory method

In this way, in addition to specifying the required class attribute, you also specify the Factory-method property to specify the method that instantiates the bean, and the static factory method allows you to specify the method parameter, which the spring IOC container invokes to get the bean by using the method specified by this property.

(1) Define the Static factory class:

Package Com.spring.factory;import Com.spring.service.iuserservice;import Com.spring.service.impl.UserServiceImpl; public class Userstaticfactory {    //factory method public    static Iuserservice newinstance (String message) {        // Returns the required bean instance        return new Userserviceimpl (message);}    }

(2) Configure the bean definition in the configuration file (Applicationcontext1.xml) as follows:

  <!--use static Factory Method--  <bean id= "bean3" class= "Com.spring.factory.UserStaticFactory" factory-method= " Newinstance ">      <constructor-arg index=" 0 "value=" Lisi "/>  </bean>

(3) test method:

/** * Using a static factory instantiation bean */@Testpublic void Testcreatebeanbystaticfactory () {    ApplicationContext ctx=new Classpathxmlapplicationcontext ("Applicationcontext1.xml");    Iuserservice bean3= (Iuserservice) Ctx.getbean ("Bean3");    Bean3.show ();}

3. Instantiate a bean using the instance factory method

You cannot specify a class property in this way, you must use the Factory-bean property to specify the method that the factory Bean,factory-method attribute specifies to instantiate the bean, and the instance factory method allows you to specify the method parameters, as in the way the constructor is used. The configuration is as follows:

(1) Define the instance factory class:

Package Com.spring.factory;import Com.spring.service.iuserservice;import Com.spring.service.impl.UserServiceImpl; public class Userinstancefactory {public        iuserservice newinstance (String message) {        return new Userserviceimpl (message);}    }

(2) Configure the bean definition in the configuration file (Applicationcontext1.xml) as follows:

  <!--1. Defining Instance factory Beans--  <bean id= "beaninstancefactory" class= "com.spring.factory.UserInstanceFactory"/ >  <!--2. Using instance factory bean to create beans--  <bean id= "Bean4" factory-bean= "Beaninstancefactory" factory-method= "Newinstance" >       <constructor-arg index= "0" value= "AAAA" ></constructor-arg>  

(3) test method:

/** * Instantiate Bean with instance factory */@Testpublic void Testcreatebeanbyinstancefactory () {    ApplicationContext ctx=new Classpathxmlapplicationcontext ("Applicationcontext1.xml");    Iuserservice bean4= (Iuserservice) Ctx.getbean ("Bean4");    Bean4.show ();}

Summarize:

These three ways are only different, from the way to get the same look, no difference. This is also the spring IOC charm, spring IOC helps you to create beans, we can just use it, is not very simple.

Third, the scope of the bean

What is a scope? That is, "scope", in object-oriented programming, generally refers to the visible range between an object or a variable. In the spring container, it refers to the requested visible range of the bean object it creates relative to other bean objects.
Spring provides two basic scopes of "singleton" and "prototype", plus three web scopes for "request", "session", "Globalsession", and spring allows users to customize their scopes.

Scope Description
Singleton

A bean definition corresponds to an object instance in each spring IOC container.

(default) There is only one bean instance in the spring IOC container, and the bean exists as a single instance.

prototype

A bean definition corresponds to multiple object instances.

Each time a bean is called from the container, it returns a new instance, which is the equivalent of executing new Xxxbean () every time Getbean () is called.

Request

In an HTTP request, a bean definition corresponds to an instance, that is, each HTTP request will have its own bean instance. They are created based on a bean definition. The scope is valid only in the case of web-based spring  ApplicationContext .

Session

In a http  session , a bean definition corresponds to an instance. The scope is valid only in the case of web-based spring  ApplicationContext . The

shares a bean with the same HTTP session, and different HTTP sessions use different beans, which apply only to the WEBAPPLICATIONCONTEXT environment.

globalsession

In a global http  Session , a bean definition corresponds to an instance. Typically, this is only valid when using the Portlet context. The scope is valid only in the case of web-based spring  ApplicationContext .

1.singleton
The bean of the "singleton" scope only has one instance in each spring IOC container, and its full life cycle is fully managed by the spring container. For all operations that get the bean, the spring container will return only the same bean. Note: Spring will set the bean's default scope to Singleton.

When the scope of a bean is set to Singleton, only one shared bean instance exists in the spring IOC container, and all requests to the bean, as long as the ID matches the bean definition, will return only the same instance of the bean. In other words, when a bean definition is set to singleton scope, the Spring IOC container only creates a unique instance of the bean definition. This single instance is stored in the singleton cache (singleton cache), and all subsequent requests and references to the bean will return the cached object instance, noting that the singleton in the singleton scope and GOF design pattern is completely different, The singleton design pattern indicates that only one class exists in a ClassLoader, and here the singleton represents a container for a bean, which means that when a bean is identified as Singleton, Only one of the beans will exist in spring's IOC container.

By default, spring's ApplicationContext container automatically instantiates all singleton beans and caches them in the container at startup.
Although it takes some time to start, it brings two benefits:
(1) The early instantiation of the bean will identify some potential configuration problems early.
(2) The next bean is saved in cache, and when the runtime is used to the bean, it is no longer instantiated, which speeds up the running efficiency.
If the user does not want the singleton bean to be instantiated in advance when the container starts, it can be controlled by the Lazy-init property. However, lazy-init= "true" beans are still instantiated in advance in some cases: if the bean is referenced by another bean that needs to be instantiated in advance, Spring ignores the deferred instantiation setting.

2.prototype

That is, the prototype, each time the request fetch bean to spring container returns a brand-new bean, relative to "singleton" is not to cache the bean, each time is a bean definition based on the creation of a new bean.

When using Prorotype as a scope, the bean causes a bean instance to be created every time a request is made to the bean, so the stateful bean should use the prorotype scope, and the stateless Bean uses the singleton scope. Also, spring cannot be responsible for the entire life cycle of a prototype-scoped bean, which, after initializing, configuring, decorating, or assembling a prototype instance, gives it to the client and then is indifferent to the prototype instance.

By default, the spring container does not instantiate the prototype bean at startup. In addition, the spring container will not manage its life cycle once the prototype bean is handed over to the caller.

Here is a test of the singleton and Prototype,java class used before the Helloworld.java.

Package Com.spring.test;public class HelloWorld {    private String info;    Public String GetInfo () {        return info;    }    public void SetInfo (String info) {        this.info = info;    }        Public HelloWorld () {        System.out.println ("Execute constructor! ");    }}

Configuration file Applicationcontext.xml:

<bean id= "Hello" class= "Com.spring.test.HelloWorld" >      <property name= "info" value= "Hello,this is my first Spring application! " ></property>  

Where the bean with id "Hello" is declared as singleton (because the default is singleton, you can not display the specified)
The test method is as follows:

/** * Test Bean scope */@Testpublic void Test () {    //Read configuration file    ApplicationContext ctx=new Classpathxmlapplicationcontext ("Applicationcontext.xml");    Gets the instance of the bean    HelloWorld t= (HelloWorld) ctx.getbean ("Hello");    HelloWorld t1= (HelloWorld) ctx.getbean ("Hello");    System.out.println (T==T1);}

The result of the execution is:

You can see that the Execute constructor is only printed once! ", and T=t1, stating that they are the same object.

Modify the configuration file to change the scope property of the bean with id "Hello" to "prototype".

<bean id= "Hello" class= "Com.spring.test.HelloWorld" scope= "prototype" >      <property name= "info" value= " Hello,this is my first Spring application! " ></property>  

Execute the above test method again, the result is as follows:

Printed two times "execution constructor!" ", and T!=t1.

Scopes in 3.web Apps

In a Web application, we may need to store the data in the request, session, global session. So spring provides three web scopes: request, session, Globalsession.

(1) Request scope : Requestindicates that a new bean is generated for each HTTP request, and that the bean is valid only within the current HTTP requests. Example:

<bean id= "loginaction" class= "com.foo.LoginAction" scope= "Request"/>

For each HTTP request, the spring container creates a completely new instance of the Loginaction bean based on the loginaction bean definition, and the loginaction bean instance is only valid within the current HTTP request. As a result, you can safely change the internal state of the built instance as needed, and other requests that are created from an instance of the Loginaction bean definition will not see these state changes specific to a request. When the processing request ends, the bean instance of the request scope is destroyed.

(2) Session scope: For each session, the spring container creates a completely new bean, and the bean is valid only within the current HTTP session.

<bean id= "userpreferences" class= "Com.foo.UserPreferences" scope= "Session"/>

For an HTTP Session , the Spring container userPreferences creates a completely new bean instance based on the bean definition userPreferences , and the userPreferences Bean is valid only within the current HTTP Session . With the request作用域 same, you can safely change the internal state of the created instance as needed, and other HTTP Session based on userPreferences the created instance will not see these Session status changes specific to an HTTP. When HTTP Session is eventually discarded, the beans within that HTTP Session scope are discarded.

(3) Globalsession scope: Similar to the session scope, just the Web application that is used for the portlet environment. If the non-portlet environment is treated as a session scope.

<bean id= "userpreferences" class= "com.foo.UserPreferences" scope= "Globalsession"/>

global sessionScopes are similar to standard HTTP Session scopes, but they are only meaningful in portlet-based Web applications. The Portlet specification defines the global Session concept, which is shared by all the different portlets that make up a portlet Web application. Beans defined in the scope global session are scoped to Session the life cycle of the global portlet.

Note that if you are writing a standard servlet-based Web application and you have defined one or more global session scoped beans, the system will use the standard HTTP Session scope and will not cause any errors.

Use of the Spring Series Bean

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.