factory-bean in spring facilitates to create bean
by factory class.
Factory
class will have:
a)non-
static methods to return the object of bean.
b)a
static method to return the instance of class itself.
<bean
id="serviceFactory" class="com.concretepage.ServiceFactory"
factory-method="createInstance"></bean>
<bean
id="userService" factory-bean="serviceFactory"
factory-method="createUserService"></bean>
<bean
id="loginService" factory-bean ="serviceFactory"
factory-method="createLoginService"></bean>
public
class ServiceFactory {
private
static UserService userService= new UserService();
private
static LoginService loginService= new LoginService();
private
static ServiceFactory serviceFactory= new ServiceFactory();
private
ServiceFactory(){}
public UserService createUserService(){
return
userService;
}
public LoginService createLoginService(){
return
loginService;
}
public
static ServiceFactory createInstance(){
return
serviceFactory;
}
}
public
class UserService {
public UserService() {
System.out.println("Initialising UserService.");
}
}
public
class LoginService {
public
LoginService(){
System.out.println("Initialising LoginService.");
}
}
public
class SpringDemo {
public static void main(String... args) {
ApplicationContext
context = new ClassPathXmlApplicationContext("spring-config.xml");
context.getBean("userService");
context.getBean("loginService");
}
}
No comments:
Post a Comment