important methods of BeanFatory interface



Que: -What are the important methods of BeanFatory interface?

  1. object getBean (String)
  2. object getBean (String, Class)
  3. boolean isSingleton (String name)
  4. boolean isPrototype (String name)
  5. boolean containtsBean (String name)
  6. String [] getAliases (String name)

A spring bean can have more than one name. Those names are known as its calling getAliases () method we can get all the alias names of the spring bean.

e.g.: -
<bean name=”hb1, hb2, hb3” class=”HelloBean”>
String s [] =container.getAliases (“hb1”);
for (int i=0; i<s.lenght; i++)
System.out.prinln (s[i]);

Output: -


Spring bean in the application is a singleton or not use can find out by calling isSingleton() method on the bean container. The following statements prints true for a bean as a spring bean is by default singleton in a spring container.


  • isProtype () method returns false for a bean unless we change its scope to prototype.
  • constantBean () method returns true if the bean definition is found in the bean configuration file with that name.

System.out.println (container.constantBean(“hb1”));

For bean instantiation overloaded getBean() method is used as follows: –

HelloBean hb= (HelloBean) container.getBean (“hb1”, HelloBean.class);

Que: – Example spring application on creating a bean instance using static factory() method?

Some java classes can be instantiated only though their static factory methods. In such a case, we should indicate to the spring container about the same by using “factory-method” attribute of <bean> tag.

To this attribute, we need to specify the factory method name as the value.


  3. beans.xml”

public class HelloBean
private String message;
public HelloBean (String m);
message =m;
public static HelloBean getInstance()
System.out.println (“In factory method”);
HelloBean hb= new HelloBean (“Instantiated from static factory method”);
return hb;
} //user defined static factory method
public void displayMessage()
System.out.println (message);


<bean name=”hb1” class=”HelloBean” factory-method=”getInstance”/>
< /beans>”

class ExecuteBean
xmlBeanFactory factory=new XmlBeanFactory (newFileSystemResource (“beans.xml”));
HelloBean hb=(HelloBean) factory.getBean (“hb1”);
Hb.displayMessage ();


Leave a Reply

Your email address will not be published. Required fields are marked *