验证Bean的singleton和portotype作用域
1.HelloWorld.java
package com.forcoldplay.spring.test02;
public class HelloWorld {
private String message ;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
System.out.println("message : " + message);
return message;
}
}
2.MainApp.java
package com.forcoldplay.spring.test02;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj1 = context.getBean("helloWorld02",HelloWorld.class);
obj1.setMessage("I am object A");
obj1.getMessage();
HelloWorld obj2 = context.getBean("helloWorld02",HelloWorld.class);
obj2.getMessage();
}
}
3.配置文件,设作用域为原型模式
<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">
<bean id="helloWorld" class="com.forcoldplay.spring.test.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
<bean id="helloWorld02" class="com.forcoldplay.spring.test02.HelloWorld" scope="prototype">
</bean>
</beans>
4.运行结果
message : I am object A
message : null
5.改为单例模式
<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd">
<bean id="helloWorld" class="com.forcoldplay.spring.test.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
<bean id="helloWorld02" class="com.forcoldplay.spring.test02.HelloWorld" scope="singleton">
</bean>
</beans>
运行结果为
message : I am object A
message : I am object A
其默认值为单例模式。