I am working on a basic @Autowired program, where I have 2 classes Alpha and Beta . Here Alpha has a dependency on Beta using @Autowired .
In the spring configuration file, more than 1 bean was created for the Beta class, so I expected an exception from spring when it tries to insert a dependency in the Alpha class, since there are 2 beta versions of beans instead of 1. But in my program I do not get any exceptions, it works great.
Here is my code:
Alpha.java
public class Alpha { @Autowired private Beta beta; public Alpha() { System.out.println("Inside Alpha constructor."); } @Override public String toString() { return "Alpha [beta=" + beta + "]"; } }
Beta.java
public class Beta { public Beta() { System.out.println("Inside Beta constructor."); } @Override public String toString() { return "This is Beta"; } }
spring -config.xml
<beans> <context:annotation-config/> <bean id="alpha" class="Alpha"> </bean> <bean id="beta" class="Beta"> </bean> <bean id="beta1" class="Beta"> </bean> <bean id="beta2" class="Beta"> </bean> </beans>
The main program:
public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Alpha alpha = (Alpha) context.getBean("alpha"); System.out.println(alpha); }
This is the conclusion:
Inside Alpha constructor. Inside Beta constructor. Inside Beta constructor. Inside Beta constructor. Alpha [beta=This is Beta]
source share