gpt4 book ai didi

java - 使用 Spring : 需要澄清

转载 作者:行者123 更新时间:2023-12-01 12:15:16 25 4
gpt4 key购买 nike

我正在学习spring标签的使用。我写了一个简单的程序。

    <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());
}

}

When I run Main class , I get below result :

First Book : DefaultName

First Book : DefaultName

Second Book : DefaultName

My Question, why is name of the firstBook not set even though I have set it : firstBook.setName("Edge of Eternity"); . When I remove aop:scoped-proxy , name is set properly. Why is default name not overwrritten ?

最佳答案

您不应该按照您现在的方式使用作用域代理 bean。范围代理 bean 在开发 - 即 - web 应用程序并将它们用作从单例 bean 引用时非常有用。

查看 Spring 文档 [1]:“您不需要将 与作用域为单例或原型(prototype)的 bean 结合使用”

[1] http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes-other-injection

关于java - 使用 Spring : <aop:scoped-proxy/> 需要澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27059342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com