if I am defining two beans of same class and not giving any scope. Then how many instance of class will get created. for example
in applicationContext.xml
<bean name="testBean" class="com.test.Example"/>
<bean name="myBean" class="com.test.Example"/>
Spring will create two beans of the type com.test.Example
and the autowiring will be for the type or method name (or Qualifiers), see Spring IOC
See this simple test:
With this class
public static class TestBean {
static int INT = 1;
public int test;
public TestBean() {
test = INT++;
}
}
Configuration xml:
<bean name="testBean" class="com.test.TestBean"/>
<bean name="myBean" class="com.test.TestBean"/>
JUnit4 with spring container test:
@Resource
TestBean testBean;
@Resource
TestBean myBean;
@Test
public void test() {
assertNotNull(testBean);
assertNotNull(myBean);
assertFalse(testBean == myBean);
assertFalse(testBean.test == myBean.test);
}
This test dont fail, as you see, two beans of type TestBean are created.
See this part in the Spring Doc:
byName
Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master, and uses it to set the property.byType
Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set.constructor
Analogous to byType, but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With