Common bean definition and initialization methods are generally implemented through the setter method or constructor of property. For example
<bean id="beanName" class="com.csdn.net.arvin.BeanClass" > <constructor-arg value="***" /> <property name="propertyOne" value="" /></bean>
This definition creates a bean object using the new com.csdn.net. Arvin. beanclass (); method. In practice, the factory mode in design mode is used to create objects in many cases. The static factory class is used to call the static methods in the factory class. For example, the public static class name getinstance () method returns the objects we actually need created based on the internal logic of the getinstance () method.
The following is a complete configuration using the xml configuration file. In spring, use the factory class to create the demo of the bean object we need.
This advantage is obvious. Even if the actually retrieved mailconfig type object changes, the code in the main method does not need to be changed.
The Code is as follows:
Main method class:
package factorybean;import injection.MailConfig;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class FactoryBeanMain{ public static void main(String[] args) { String springConfig = "factorybean/spring-config.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(springConfig); MailConfig mailConfig = context.getBean("mailConfig", MailConfig.class); mailConfig.doIt(); }}
Spring-config.xml:
<?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"><bean id="mailConfig" class="factorybean.StaticMailConfigFactory"factory-method="getMailConfig"><constructor-arg value="companyTwo" /></bean></beans>
Static factory class:
package factorybean;import injection.MailConfig;public class StaticMailConfigFactory{ public static MailConfig getMailConfig(String mailServiceProvider) { if ("companyOne".equals(mailServiceProvider)) return new MailConfigOfCompanyOne(); if ("companyTwo".equals(mailServiceProvider)) return new MailConfigOfCompanyTwo(); return null; }}
Mailconfig interface:
package injection;public interface MailConfig{ public void doIt();}
The mailconfigofcompanyone class that implements the mailconfig interface:
package factorybean;import injection.MailConfig;public class MailConfigOfCompanyOne implements MailConfig{ @Override public void doIt() { System.out.print("companyOne's mailConfig is created."); }}
Mailconfigofcompanytwo class that implements the mailconfig interface:
package factorybean;import injection.MailConfig;public class MailConfigOfCompanyTwo implements MailConfig{ @Override public void doIt() { System.out.print("companyTwo's mailConfig is created."); }}