important methods of BeanFatory interface

previous-button-hisubmit-hi

 

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 aliases.by 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: -
hb2

hb3

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.

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

  • 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.

Factorymethodinstantiation

  1. HelloBean.java
  2. ExecuteBean.java
  3. beans.xml

HelloBean.java”

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);
}
}

beans.xml”

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

ExecuteBean.java”

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

previous-button-hisubmit-hi

Leave a Reply

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