[Spring 3] spring bean and Spring bean

Source: Internet
Author: User

[Spring 3] spring bean and Spring bean
Environment preparation

  • Create a simple maven project in Eclipse. Select maven-archetype-quickstart for the Artifact Id;
  • Add the spring-context dependency;
        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-context</artifactId>            <version>3.2.16.RELEASE</version>        </dependency>
  • Add spring configuration file spring. xml under the resources Directory;
  • Write bean and test code;
Bean creation method default constructor create bean

First, write an acrobatics class;

Package cn.edu. hdu. sia. chapter2; public class Juggler implements extends mer {private int beanBags = 3; public Juggler () {} public Juggler (int beanBags) {this. beanBags = beanBags;} public void perform () throws ceceexception {System. out. println ("JUGGLING" + beanBags + "BEANBAGS ");}}View Code

Declare the acrobat Bean in the spring configuration file (<constructor-arg> is not configured, and the default constructor is used );

  <bean id="duke" class="cn.edu.hdu.sia.chapter2.Juggler">  </bean>

Use the acrobatics bean in the main method;

    public static void main(String[] args) {        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");        Performer performer = (Performer) ctx.getBean("duke");        performer.perform();    }
Create bean using non-default constructor

Case where the constructor parameter is of the basic data type

In the preceding example, you can input parameters to the constructor When configuring the bean. The following configuration will call the public Juggler (int beanBags) constructor to create the constructor bean;

  <bean id="duke" class="cn.edu.hdu.sia.chapter2.Juggler">    <constructor-arg value="15" />  </bean>

Case where the constructor parameter is of the Object Reference Type

Now, we will add poems to the acrobatics;

First define a poetry recitation interface:

package cn.edu.hdu.sia.chapter2;public interface Poem {    public void recite();}

Write another implementation class:

Package cn.edu. hdu. sia. chapter2; public class JingYeSi implements Poem {public void recite () {System. out. println ("Moonlight before bed ~ ");}}

Then write the poems and tricks:

Package cn.edu. hdu. sia. chapter2; public class PoeticJuggler extends Juggler {private Poem poem; public PoeticJuggler (int beanBags, Poem poem) {super (beanBags); this. poem = poem;}/*** @ see cn.edu. hdu. sia. chapter2.Juggler # perform () * @ throws PerformanceException */@ Override public void perform () throws ceceexception {super. perform (); poem. recite ();}}View Code

Declare the acrobatics Bean in the spring configuration file. Note that the second parameter of the constructor is the object reference and the bean with id "jingyesi" is referenced;

You can use the index attribute to specify the index subscript and type of the constructor parameter.ConstructorParametersType, specified by nameConstructorParameter Name, used to distinguish different parameters;

    <bean id="jingyesi" class="cn.edu.hdu.sia.chapter2.JingYeSi">    </bean>        <bean id="poeticDuke" class="cn.edu.hdu.sia.chapter2.PoeticJuggler">        <constructor-arg value="15" />        <constructor-arg ref="jingyesi" />    </bean>

Finally, based on the preceding main method to test the execution of the perform, it is found that the acrobatics Bean can not only play around, but also recite poems;

Create bean using factory Method

When the constructor method is private, bean cannot be created through the constructor method. At this time, bean is generally created through the factory method. The following is a typical Singleton class, the constructor is a private property:

package cn.edu.hdu.sia.chapter2;public class Stage {    private Stage() {    }    private static class StageSingletonHolder {        static Stage stage = new Stage();    }    public static Stage getInstance() {        return StageSingletonHolder.stage;    }        public void printDescription(){        System.out.println("this is a stage.");    }}

To create the bean, configure the bean in the spring configuration file as follows:

You can use the factory-bean attribute to set the specified factory bean and use the <constructor-arg> label to pass in parameters to the factory-method;

<bean id="theStage" class="cn.edu.hdu.sia.chapter2.Stage" factory-method="getInstance" />
Bean Scope

All beans in the spring context are "Singleton" by default, that is, there is only one instance. Note that the singleton here refers to the singleton within the spring context; to modify this configuration item, you only need to configure the scope attribute. The default scope is singleton. The configurable attribute values are listed as follows:

Scope

Definition

Singleton

In each Spring container, a Bean defines only one object instance (default)

Prototype

The runtime Bean definition can be instantiated at any time (an instance is created for each call)

Request

In an HTTP request, each Bean defines an instance. This scope is valid only in the Web-based Spring context (such as Spring MVC ).

Session

In an HTTP Session, each Bean definition corresponds to an instance. This scope is only valid in the Web-based Spring context (such as Spring MVC ).

Global-session

In a global HTTP Session, each Bean definition corresponds to an instance. This scope is only valid in the Portlet context.

Bean initialization and destruction

Bean initialization refers to some operations performed after bean objects are created, such as initialization;

Bean destruction refers to some operations performed when the bean is removed from the spring context, such as cleaning and releasing resources;

You can configure the init-method and destroy-method attributes of bean and specify its initialization method and destruction method. The configuration is as follows:

    <bean id="theStage" class="cn.edu.hdu.sia.chapter2.Stage" factory-method="getInstance"           init-method="init" destroy-method="destroy"/>

Among them, init and destroy are the custom methods of the bean. You can add some initialization and destruction operations in them;

In addition, we can implement the InitializingBean and DisposableBean interfaces to initialize and destroy the bean. We need to implement the following two methods:

    /**     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()     * @throws Exception     */    public void afterPropertiesSet() throws Exception {        // TODO Auto-generated method stub    }    /**     * @see org.springframework.beans.factory.DisposableBean#destroy()     * @throws Exception     */    public void destroy() throws Exception {        // TODO Auto-generated method stub    }

The disadvantage of implementing these interfaces is that beans are coupled with spring APIs. Therefore, we recommend that you use the init-method and destroy-method attributes to initialize and destroy them;

Additionally, in non-web applications, you can call the close method or the registerShutdownHook method to disable the spring context. The differences are as follows:

Close: immediately close the spring context (container );

RegisterShutdownHook: Shut down the spring context (container) When JVM is disabled );

As shown in the following code snippet, the bean destruction method will not be executed immediately, but will be executed only after JVM destruction:

    public static void main(String[] args) {        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");        Stage stage = (Stage) ctx.getBean("theStage");        stage.printDescription();        ctx.registerShutdownHook();        try {            TimeUnit.MILLISECONDS.sleep(1000);        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }                System.out.println("start JVM desdroy.");    }
Configure the bean attribute as the basic data type (the setter method is required in the bean)
    <bean id="peter" class="cn.edu.hdu.sia.chapter2.User">        <property name="name" value="Peter"></property>        <property name="age" value="22"></property>    </bean>
When bean attributes are referenced by objects

Attribute bean injection through external

    <bean id="jingyesi" class="cn.edu.hdu.sia.chapter2.JingYeSi"></bean>        <bean id="peter" class="cn.edu.hdu.sia.chapter2.User">        <property name="name" value="Peter"></property>        <property name="age" value="22"></property>        <property name="poem" ref="jingyesi"></property>    </bean>

Attribute beans are injected internally,It is also applicable to the constructor-arg parameter of the constructor. Note: External beans cannot reference internal beans.

    <bean id="peter" class="cn.edu.hdu.sia.chapter2.User">        <property name="name" value="Peter"></property>        <property name="age" value="22"></property>        <property name="poem">            <bean class="cn.edu.hdu.sia.chapter2.JingYeSi"/>        </property>    </bean>

In addition, you can use the p namespace of spring to configure attributes:

<bean id="peter" class="cn.edu.hdu.sia.chapter2.User" p:name="Peter" p:age="22" />
When bean attributes are set

The following four configurations can be used:

 

Set Element

Purpose

Actual data type

<List>

Value of the list type assembly. Repeated values are allowed.

Array or java. util. Collection

<Set>

The set type value cannot be repeated.

<Map>

Value of the Assembly map type. The name and value can be of any type.

Java. util. Map

<Props>

Value of the Assembly properties type. The name and value must be String type.

Java. util. Properties

 

List, Set, Array

Here, the list can also be replaced with set. The difference is that repeated lists are not allowed.

    <bean id="jingyesi" class="cn.edu.hdu.sia.chapter2.JingYeSi"></bean>    <bean id="xinglunan" class="cn.edu.hdu.sia.chapter2.XingLuNan"></bean>        <bean id="peter" class="cn.edu.hdu.sia.chapter2.User">        <property name="name" value="Peter"></property>        <property name="age" value="22"></property>        <property name="poemList">            <list>                <ref bean="jingyesi" />                <ref bean="xinglunan" />            </list>        </property>    </bean>

Map

    <bean id="jingyesi" class="cn.edu.hdu.sia.chapter2.JingYeSi"></bean>    <bean id="xinglunan" class="cn.edu.hdu.sia.chapter2.XingLuNan"></bean>        <bean id="peter" class="cn.edu.hdu.sia.chapter2.User">        <property name="name" value="Peter"></property>        <property name="age" value="22"></property>        <property name="poemMap">            <map>                <entry key="jingyesi" value-ref="jingyesi"/>                <entry key="xinglunan" value-ref="xinglunan"/>            </map>        </property>    </bean>

Properties

    <bean id="peter" class="cn.edu.hdu.sia.chapter2.User">        <property name="name" value="Peter"></property>        <property name="age" value="22"></property>        <property name="properties">            <props>                <prop key="test1">111</prop>                <prop key="test2">222</prop>            </props>        </property>    </bean>
When the bean property value is set to null
    <bean id="peter" class="cn.edu.hdu.sia.chapter2.User">        <property name="name" value="Peter"></property>        <property name="age" value="22"></property>        <property name="properties">         <null/>        </property>    </bean>
Download demo code

Http://files.cnblogs.com/files/chenpi/sia.7z

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.