Java 使用Spring需要澄清:<;aop:作用域代理/>;
我在春天学习标签的用法。我写了一个简单的程序Java 使用Spring需要澄清:<;aop:作用域代理/>;,java,spring,Java,Spring,我在春天学习标签的用法。我写了一个简单的程序 <bean id="book" class="com.test.scoped.Book" scope="prototype" > <property name="name" value="DefaultName"></property> <aop:scoped-proxy/> </bean> <bean id="reader" cl
<bean id="book" class="com.test.scoped.Book" scope="prototype" >
<property name="name" value="DefaultName"></property>
<aop:scoped-proxy/>
</bean>
<bean id="reader" class="com.test.scoped.Reader" >
<property name="book" ref="book" />
</bean>
public class Book {
private String name;
public String toString (){
return this.name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Reader {
private Book book;
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx = new ClassPathXmlApplicationContext("ScopedProxy.xml");
Book firstBook = ((Reader)ctx.getBean("reader")).getBook();
System.out.println("First Book : "+firstBook.getName());
firstBook.setName("Edge of Eternity");
System.out.println("First Book : "+firstBook.getName());
Book secondBook = ((Reader)ctx.getBean("reader")).getBook();
System.out.println("Second Book : "+secondBook.getName());
}
}
我的问题是,为什么即使我已经设定了第一本书的名字,它也并没有设定:firstBook.setName(“永恒的边缘”)。当我删除aop:scoped代理时,名称设置正确。
为什么默认名称没有过度使用
您不应该像现在这样使用作用域代理bean。作用域代理bean在开发webapps并将其用作单例bean的引用时非常有用
查看Spring文档[1]:“如果您的主要目标是为属性
名称设置默认值,则无需使用,只需
<bean id="book" class="eu.europa.ema.esubmission.psur.Book" scope="prototype" >
<property name="name" value="DefaultName"></property>
</bean>
然后,如果愿意,可以覆盖属性名称
然后关于aop:scope代理
,它与bean
完全无关,而不是scope=session
bean
如果您想将会话范围
bean作为依赖项注入到其他bean
中,那么只有您应该使用范围代理
声明。因为您的书籍
bean被定义为原型
它不需要
<bean id="book" class="eu.europa.ema.esubmission.psur.Book" scope="prototype" >
<property name="name" value="DefaultName"></property>
</bean>