我需要自我注入原型bean。據(jù)我所知,如果 bean scope="singleton" 是可能的,但在這種情況下,我從 spring 收到消息:“應(yīng)用程序上下文中某些 bean 的依賴(lài)關(guān)系形成一個(gè)循環(huán):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); }}調(diào)用:@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..."); }}如何改進(jìn)我的代碼?
2 回答

胡子哥哥
TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超6個(gè)贊
我認(rèn)為你init()正在形成一個(gè)循環(huán)。
當(dāng)你在PostOffice課堂上調(diào)用它時(shí)
PostMans2 thr = ctx.getBean(PostMans2.class);
PostMans2 類(lèi)將被引用。
在PostMans2你已經(jīng)定義了init()哪個(gè)將再次引用PostMans2,這將繼續(xù)
因此,嘗試消除init()從PostMan2所有應(yīng)該罰款
@PostConstruct
private void init() {
postman = ctx.getBean(PostMans2.class);
}

米琪卡哇伊
TA貢獻(xiàn)1998條經(jīng)驗(yàn) 獲得超6個(gè)贊
為什么你需要通過(guò) Spring 來(lái)獲得這個(gè)實(shí)例?
看起來(lái)你想要這樣做:
@PostConstruct
private void init() {
postman = this;
}
添加回答
舉報(bào)
0/150
提交
取消