デフォルトの単一インスタンスの場合、フィールド循環依存によってエラーが報告されることはなく、相互依存を実現できます。
@Component
public class BeanA {
private static final Logger logger = LoggerFactory.getLogger(BeanA.class);
@Autowired
private BeanB beanB;
public void print() {
logger.info("hello springboot !");
}
}
@Component
public class BeanB {
private static final Logger logger = LoggerFactory.getLogger(BeanB.class);
@Autowired
private BeanA beanA;
public void print() {
logger.info("hello springboot !");
}
}
循環依存関係を構築するときにエラーを直接報告する
例外情報:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| beanA defined in file [D:\workspaces\demo\target\classes\com\example\demo\bean2\BeanA.class]
↑ ↓
| beanB defined in file [D:\workspaces\demo\target\classes\com\example\demo\bean2\BeanB.class]
└─────┘
@Component
public class BeanA {
private static final Logger logger = LoggerFactory.getLogger(BeanA.class);
private BeanB beanB;
public BeanA(BeanB beanB) {
this.beanB = beanB;
}
public void print() {
logger.info("hello springboot !");
}
}
@Component
public class BeanB {
private static final Logger logger = LoggerFactory.getLogger(BeanB.class);
private BeanA beanA;
public BeanB(BeanA beanA) {
this.beanA = beanA;
}
public void print() {
logger.info("hello springboot !");
}
}
非シングルトンの循環依存関係。起動時にエラーは報告されませんが、Beanが取得されるとエラーが報告されます。
异常信息:要求されたBeanは現在作成中です:解決できない循環参照はありますか?
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BeanA {
private static final Logger logger = LoggerFactory.getLogger(BeanA.class);
@Autowired
private BeanB beanB;
public void print() {
logger.info("hello springboot !");
}
}
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class BeanB {
private static final Logger logger = LoggerFactory.getLogger(BeanB.class);
@Autowired
private BeanA beanA;
public void print() {
logger.info("hello springboot !");
}
}
テストコード
@SpringBootApplication
public class DemoApplication {
private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
BeanA bean = context.getBean(BeanA.class);
bean.print();
}
}