On the way learning spring 2

 

Spring 10 - Bean scope

 

Prototype; Request ;Session; Singleton.

Source Code:

Person person1 =  (Person) context.getBean("person");
Person person2 =  (Person) context.getBean("person");
        
person1.setTaxId(666);
        
System.out.println(person2);

Result:

Person [id=777, name=Mary, taxId=666, address=Address [street=hillside, pos=08540]]

Default behave(Singleton): No matter how many times you request this beans from the container, will always be given the same bean.

 

Change scope to prototype

<bean id="person"
class="com.caveofprogramming.spring.test.Person"
        scope="prototype">

Result:

Person [id=777, name=Mary, taxId=123, address=Address [street=hillside, pos=08540]]

 

 

Spring 11 - Init and Destroy Methods

 

1.Add method onCreate() in Person.class. 

public void onCreate(){
        System.out.println("Person created: " + this);
    }

2.Set Init-method in beans.xml  to  onCreate

Result:

Person created: Person [id=777, name=Mary, taxId=123, address=Address [street=hillside, pos=08540]]
Person created: Person [id=777, name=Mary, taxId=123, address=Address [street=hillside, pos=08540]]
Person [id=777, name=Mary, taxId=123, address=Address [street=hillside, pos=08540]]

 

 

3.Add method onDestroy() in Person.class

    public void onDestroy(){
        System.out.println("Person destroyed.");
    }

4.Set destroy-method in beans.xml to toDestroy

Result:

Person created: Person [id=777, name=Mary, taxId=123, address=Address [street=hillside, pos=08540]]
Person created: Person [id=777, name=Mary, taxId=123, address=Address [street=hillside, pos=08540]]
Person [id=777, name=Mary, taxId=123, address=Address [street=hillside, pos=08540]]

5. Set scope back to singleton(default)

Result:

Person created: Person [id=777, name=Mary, taxId=123, address=Address [street=hillside, pos=08540]]
Person [id=777, name=Mary, taxId=666, address=Address [street=hillside, pos=08540]]
Person destroyed.

 

posted on 2015-10-17 00:38  jobfinder  阅读(125)  评论(0编辑  收藏  举报