【问题标题】:Self injecting prototype bean - cyclic reference自注入原型 bean - 循环引用
【发布时间】:2018-08-02 03:19:05
【问题描述】:

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

    }


}

如何改进我的代码?

【问题讨论】:

    标签: java spring spring-bean


    【解决方案1】:

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

    当你在 PostOffice 类中调用它时

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

    PostMans2 类将被引用。

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

    所以尝试从PostMan2 中删除init(),一切都会好起来的

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

    【讨论】:

    • 你不明白。我故意使用循环引用。但问题是为什么我不能在原型 bean 中使用它?
    • 好吧,就像您告诉 A 呼叫 B 和 B 呼叫 A 一样。这个过程永远不会结束。所以 spring 抛出错误。
    【解决方案2】:

    为什么需要通过 Spring 来获取 this 的实例?

    看起来你想这样做:

    @PostConstruct
    private void init() {
        postman = this;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多