pmad
pmad

Reputation: 1677

what happen if we won't specify id and name attributes in bean tag of spring configuration file

if id and name attributes are not placed in , then how spring container will create a object for the class and what name it will take if multiple same classes are configured in the spring configuration file

Upvotes: 0

Views: 159

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

@HenriqueMiranda describes the naming convention. I would also add that such beans (let's call them anonymous) are often used when declared inside another bean:

<bean id="someBean" class="SomeBean">
    <property name="dependency">
        <bean class="Dependency"/>  <!-- anonymous here -->
    </property>
</bean>

Upvotes: 1

Henrique Miranda
Henrique Miranda

Reputation: 994

If you do not define a name/id for the class spring will set a default name that is:

com.mypackage.MyClass#0 //For the first object by MyClass
com.mypackage.MyClass#1 //For the second object by MyClass

When you try to access this object though the context asking for type, spring will return an exception for you (No unique bean of type). But you can access asking for the context by name.

MyClass m0 = (MyClass)appContext.getBean("com.mypackage.MyClass#0"); // This work
MyClass m1 = (MyClass)appContext.getBean("com.mypackage.MyClass#1"); // This work
MyClass m2 = (MyClass)appContext.getBean(MyClass.class); // This DOES NOT work

Upvotes: 1

Related Questions