Factory Code:
[Java]
Package factorybean;
Import injection. MailConfig;
Public class NonStaticMailConfigFactory
{
Public MailConfig getMailConfig (String mailServiceProvider)
{
If ("companyOne". equals (mailServiceProvider ))
Return new MailConfigOfCompanyOne ();
If ("companyTwo". equals (mailServiceProvider ))
Return new MailConfigOfCompanyTwo ();
Return null;
}
}
The only difference between this factory class method and the method used to retrieve objects in the factory class created Bean in the previous static factory class is that it is not static.
Compared with the factory class using the static method, the XML configuration of non-static factory classes in Spring is also a little different.
[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<Beans xmlns = "http://www.springframework.org/schema/beans"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd>
<! -- Define the Bean of the factory class first -->
<Bean id = "mailConfigFactory" class = "factorybean. StaticMailConfigFactory"/>
<! -- Here, the factory-bean label attribute takes the Bean Id of the factory class defined above, and then defines the non-static method used to obtain the object in this factory class through the factory-method label attribute -->
<Bean name = "mailConifg"
Factory-bean = "mailConfigFactory"
Factory-method = "getMailConfig"
<Constructor-arg value = "companyTwo"/>
<! -- As shown above, the constructor-arg label is still used to define the parameter for the factory class to get the object method -->
</Bean>
</Beans>
Static Method factory class create Bean has more detailed complete code reference: http://blog.csdn.net/arvinrong/article/details/7734709
The method for obtaining the class in the Client code remains unchanged:
[Java]
MailConfig mailConfig = context. getBean ("mailConfig", MailConfig. class );
Author: arvinrong