Similar to the static factory class created bean in the previous article, the only difference is that the method for obtaining the actual object in the factory class, for example, getinstance () is not a static method (non-static ).
Factory Code:
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; }}
Methods of this factory class and the previous articleCreate bean for static factory classThe only difference between getting object methods in the factory class in 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.
<? 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"> <! -- First define the bean of the factory class --> <bean id = "mailconfigfactory" class = "factorybean. staticmailconfigfactory"/> <! -- Here, the factory-bean tag attribute takes the bean ID of the factory class defined above, the factory-method label attribute is used to define the non-static method used to obtain the object in this factory class --> <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 obtain 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:
MailConfig mailConfig = context.getBean("mailConfig", MailConfig.class);