2

I need to self-inject prototype bean. As I know, it is possible if bean scope="singleton", but in this case I get message from spring : "The dependencies of some of the beans in the application context form a cycle: postMan2"

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

}

Invoking:

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

    }


}

How to improve my code?

Leo
  • 1,029
  • 4
  • 19
  • 40

2 Answers2

0

I think your init() is forming a Cycle.

When you call this in PostOffice class

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

PostMans2 class will be refered.

In PostMans2 you have defined init() which will again refer PostMans2 and this will go on

So try removing init() from PostMan2 and all should be fine

@PostConstruct
private void init() {
    postman = ctx.getBean(PostMans2.class);
}
MyTwoCents
  • 7,284
  • 3
  • 24
  • 52
  • you didn't understand. I deliberately use cyclic reference. but problem is why I can't use it in prototype beans? – Leo Aug 02 '18 at 05:58
  • Well its like you are telling A to Call B and B to Call A . This process will never end. So spring is throwing error. – MyTwoCents Aug 02 '18 at 06:01
0

Why do you need to go through Spring to get instance of this?

Looks like what you want to do it this:

@PostConstruct
private void init() {
    postman = this;
}
Rots
  • 728
  • 9
  • 20