Mostly the beans that are configure in the spring application context will be created by calling one of the class's constructor.
In the case of configuring singleton class(class that only create one instance) or bean allowing throw factory method.
Here illustrate a example to understand it-
Directory Structure-
Class FactoryBean.java
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="factoryBean" class="com.test.FactoryBean" factory-method="getInstance">
<property name="name" value="Factory Beans"></property>
</bean>
</beans>
Output is=
In the case of configuring singleton class(class that only create one instance) or bean allowing throw factory method.
Here illustrate a example to understand it-
Directory Structure-
Class FactoryBean.java
package com.test;
public class FactoryBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private FactoryBean(){}
private static class SingaltonClass // inner class who create only single instance
{
static FactoryBean instance=new FactoryBean();
}
public static FactoryBean getInstance() // factory method to create instance
{
return SingaltonClass.instance;
}
public void show()
{
System.out.println("Name is="+name);
}
}
class Main.javapublic class FactoryBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private FactoryBean(){}
private static class SingaltonClass // inner class who create only single instance
{
static FactoryBean instance=new FactoryBean();
}
public static FactoryBean getInstance() // factory method to create instance
{
return SingaltonClass.instance;
}
public void show()
{
System.out.println("Name is="+name);
}
}
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String args[])
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
FactoryBean fact=ctx.getBean("factoryBean", FactoryBean.class);
fact.show();
}
}
spring.xmlimport org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String args[])
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("spring.xml");
FactoryBean fact=ctx.getBean("factoryBean", FactoryBean.class);
fact.show();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="factoryBean" class="com.test.FactoryBean" factory-method="getInstance">
<property name="name" value="Factory Beans"></property>
</bean>
</beans>
Output is=
Name is=Factory Beans
For Further Reading,
0 comments:
Post a Comment