package com.h3.customer.services;
public class customerservice
{
string message;
public string getmessage() {
return message;
}
public void setmessage(string message) {
this.message = message;
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="customerservice"
class="com.h3.customer.services.customerservice" />
</beans>
执行结果:
package com.h3.common;
import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
import com.h3.customer.services.customerservice;
public class app
{
public static void main( string[] args )
{
applicationcontext context =
new classpathxmlapplicationcontext(new string[] {"spring-customer.xml"});
customerservice custa = (customerservice)context.getbean("customerservice");
custa.setmessage("message by custa");
system.out.println("message : " + custa.getmessage());
//retrieve it again
customerservice custb = (customerservice)context.getbean("customerservice");
system.out.println("message : " + custb.getmessage());
}
}
输出结果
message : message by custa message : message by custa
由于 bean 的 “customerservice' 是单例作用域,第二个通过提取”custb“将显示消息由 ”custa' 设置,即使它是由一个新的 getbean()方法来提取。在单例中,每个spring ioc容器只有一个实例,无论多少次调用 getbean()方法获取它,它总是返回同一个实例。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="customerservice" class="com.h3.customer.services.customerservice"
scope="prototype"/>
</beans>
运行-执行
message : message by custa message : null
package com.h3.customer.services;
import org.springframework.context.annotation.scope;
import org.springframework.stereotype.service;
@service
@scope("prototype")
public class customerservice
{
string message;
public string getmessage() {
return message;
}
public void setmessage(string message) {
this.message = message;
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemalocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.h3.customer" />
</beans>