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

我需要自我注入原型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);

    }


}

调用:


@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...");


    }



}

如何改进我的代码?


白板的微信
浏览 152回答 2
2回答

胡子哥哥

我认为你init()正在形成一个循环。当你在PostOffice课堂上调用它时PostMans2 thr = ctx.getBean(PostMans2.class);PostMans2 类将被引用。在PostMans2你已经定义了init()哪个将再次引用PostMans2,这将继续因此,尝试消除init()从PostMan2所有应该罚款@PostConstructprivate void init() {&nbsp; &nbsp; postman = ctx.getBean(PostMans2.class);}

米琪卡哇伊

为什么你需要通过 Spring 来获得这个实例?看起来你想要这样做:@PostConstructprivate void init() {&nbsp; &nbsp; postman = this;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java