在spring的配置中,默认情况下,bean都是单例的(singleton)。无论获取多少次,获取到的都是同一个bean
有两种方式可以对Bean作用域的设置
1、java配置文件
package com.zhouym.condition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope(value="prototype")
public class Book {
private int id;
private String bookName;
public Book() {
}
public Book(int id, String bookName) {
this.id = id;
this.bookName = bookName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
@Override
public String toString() {
return "Book [id=" + id + ", bookName=" + bookName + "]";
}
}
2、xml配置文件
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.zhouym.condition.Book" scope="prototype">
<property name="id" value="1" />
<property name="bookName" value="权利的游戏"/>
</bean>
</beans>