gpt4 book ai didi

java - 自注入(inject)原型(prototype)bean - 循环引用

转载 作者:太空宇宙 更新时间:2023-11-04 10:16:37 24 4
gpt4 key购买 nike

我需要自注入(inject)原型(prototype)bean。据我所知,如果beanscope =“singleton”,这是可能的,但在这种情况下,我从spring收到消息:“应用程序上下文中某些bean的依赖关系形成一个循环:postMan2”

我的 bean :

@Service
@Scope("prototype")
public class PostMan2 implements PostMans2 {

private PostMans2 postman;

@Async
public Future<String> deliverLetter(String message, int i) {
postman.test();
String res = "result!";
return new AsyncResult<String>(res);
}

@Override
public void test() {
System.out.println("Self injection example thread name="+name);
}

@PostConstruct
private void init() {
postman = ctx.getBean(PostMans2.class);
}

}

调用:

@Service
public class PostOffice implements PostOffices {

@Autowired
ApplicationContext ctx;

@Override
public void creatingPostmans() {
PostMans2 thr = ctx.getBean(PostMans2.class);
Future<String> fut = thr.deliverLetter("Some letter", 100);
while (!fut.isDone()) {
Thread.sleep(1000);
}
System.out.println("ending of PostMan's jobs...");

}


}

如何改进我的代码?

最佳答案

我认为你的init()正在形成一个循环。

当您在 PostOffice 类中调用此方法时

PostMans2 thr = ctx.getBean(PostMans2.class);

PostMans2 类将被引用。

PostMans2 中,您定义了 init() ,它将再次引用 PostMans2 并且这将继续

所以尝试从 PostMan2 中删除 init() ,一切都应该没问题

@PostConstruct
private void init() {
postman = ctx.getBean(PostMans2.class);
}

关于java - 自注入(inject)原型(prototype)bean - 循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51645001/

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