为了账号安全,请及时绑定邮箱和手机立即绑定

自注入原型bean——循环引用

自注入原型bean——循环引用

白板的微信 2021-06-20 12:15:37
我需要自我注入原型bean。据我所知,如果 bean scope="singleton" 是可能的,但在这种情况下,我从 spring 收到消息:“应用程序上下文中某些 bean 的依赖关系形成一个循环:postMan2”我的豆子:@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);    }}调用:@Servicepublic 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...");    }}如何改进我的代码?
查看完整描述

2 回答

?
胡子哥哥

TA贡献1825条经验 获得超6个赞

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


当你在PostOffice课堂上调用它时


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

PostMans2 类将被引用。


在PostMans2你已经定义了init()哪个将再次引用PostMans2,这将继续


因此,尝试消除init()从PostMan2所有应该罚款


@PostConstruct

private void init() {

    postman = ctx.getBean(PostMans2.class);

}


查看完整回答
反对 回复 2021-06-23
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

为什么你需要通过 Spring 来获得这个实例?


看起来你想要这样做:


@PostConstruct

private void init() {

    postman = this;

}


查看完整回答
反对 回复 2021-06-23
  • 2 回答
  • 0 关注
  • 151 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信