关键代码:
Markup
<!-- scope="singleton":默认值,生命周期只创建一个bean,单例模式 -->
<bean id="user1" scope="singleton" class="com.shuoeasy.test.User">
<constructor-arg name="id" value="1001"></constructor-arg>
<constructor-arg name="name" value="singleton"></constructor-arg>
</bean>
<!-- scope="prototype":原型的,每次请求都会创建一个新的bean -->
<bean id="user2" scope="prototype" class="com.shuoeasy.test.User">
<constructor-arg name="id" value="1002"></constructor-arg>
<constructor-arg name="name" value="prototype"></constructor-arg>
</bean>
详细:
User.java
Java
package com.shuoeasy.test;
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(int id, String name){
this.id = id;
this.name = name;
System.out.println(this);
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
bean.xml:
Markup
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- scope="singleton":默认值,生命周期只创建一个bean,单例模式 -->
<bean id="user1" scope="singleton" class="com.shuoeasy.test.User">
<constructor-arg name="id" value="1001"></constructor-arg>
<constructor-arg name="name" value="singleton"></constructor-arg>
</bean>
<!-- scope="prototype":原型的,每次请求都会创建一个新的bean -->
<bean id="user2" scope="prototype" class="com.shuoeasy.test.User">
<constructor-arg name="id" value="1002"></constructor-arg>
<constructor-arg name="name" value="prototype"></constructor-arg>
</bean>
</beans>
Main.java:
Java
package com.shuoeasy.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
User user1 = (User) ctx.getBean("user1");
user1 = (User) ctx.getBean("user1");
user1 = (User) ctx.getBean("user1");
User user2 = (User) ctx.getBean("user2");
user2 = (User) ctx.getBean("user2");
user2 = (User) ctx.getBean("user2");
}
}
输出:
User [id=1001, name=singleton]
User [id=1002, name=prototype]
User [id=1002, name=prototype]
User [id=1002, name=prototype]