码迷,mamicode.com
首页 > 编程语言 > 详细

On the way learning spring 2

时间:2015-10-17 01:50:40      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

 

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.

 

On the way learning spring 2

标签:

原文地址:http://www.cnblogs.com/patrickspring/p/4886758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!