i am using spring 3, and i have two beans of view scope:
1- Bean1:
@Component(\"bean1\")
@Scope(\"view\")
public class Bean1 {
@Aut
i encountered this error in quite a stupid way
@Autowired
// private Bean bean;
public void myMethod() {
return;
}
what happened is that I commented a line for some reason and left the annotation which made spring think that the method needs to be autowired
In general, the way to deal with circular dependencies is to use setter injection.
I tried the setter injection code that you posted, and it worked for me. I would imagine the reason you are getting the exception is because Bean1 and Bean2 are in the com.myapp.beans package, and you don't have component scanning enabled for that package.
You'd need to add the following to your spring configuration:
<context:component-scan base-package="com.bullethq.accounts.web"/>
or move the beans to a package which is being automatically scanned by Spring.
Spring uses an special logic for resolving this kind of circular dependencies with singleton beans. But this won't apply to other scopes. There is no elegant way of breaking this circular dependency, but a clumsy option could be this one:
@Component("bean1")
@Scope("view")
public class Bean1 {
@Autowired
private Bean2 bean2;
@PostConstruct
public void init() {
bean2.setBean1(this);
}
}
@Component("bean2")
@Scope("view")
public class Bean2 {
private Bean1 bean1;
public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
}
}
Anyway, circular dependencies are usually a symptom of bad design. You would think again if there is some better way of defining your class dependencies.
I think you could use Spring's
@Lazy
annotation on one of the autowired fields to break circular dependency.
I'm not sure if this works/exists in mentioned Spring version.
In general, the most appropriated way to avoid this problem, (also because of better Mockito integration in JUnit) is to use the Setter/Field Injection as described at https://www.baeldung.com/circular-dependencies-in-spring and at https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html
@Component("bean1")
@Scope("view")
public class Bean1 {
private Bean2 bean2;
@Autowired
public void setBean2(Bean2 bean2) {
this.bean2 = bean2;
}
}
@Component("bean2")
@Scope("view")
public class Bean2 {
private Bean1 bean1;
@Autowired
public void setBean1(Bean1 bean1) {
this.bean1 = bean1;
}
}
In my case, I was defining a bean and autowiring it in the constructor of the same class file.
@SpringBootApplication
public class MyApplication {
private MyBean myBean;
public MyApplication(MyBean myBean) {
this.myBean = myBean;
}
@Bean
public MyBean myBean() {
return new MyBean();
}
}
My solution was to move the bean definition to another class file.
@Configuration
public CustomConfig {
@Bean
public MyBean myBean() {
return new MyBean();
}
}