静态工厂)"/>
Spring实现bean的创建(静态工厂)
Bean相关配置
创建Bean对象的不同方式
-
new 对象(反射)创建对象
-
工厂创建对象
-
静态工厂创建对象 (调用工厂类中的静态方法获取对象)
-
实例工厂创建对象 (先实例化工厂-创建工厂对象,再调用工厂对象中的普通方法)
-
自己使用工厂模式创建对象
public class Account {private Integer id;private String name;private Double balance;// get set toString省略...
}
//对象工厂: 创建对象
//静态工厂: 不用创建对象,直接调用工厂类中的静态方法创建对象(访问的是静态方法)
//实例工厂: 需要创建工厂对象,再公共工厂对象调用方法创建对象(访问的是非静态方法)
public class AccountFactory {//非静态方法public Account getAccount(){return new Account();}//静态方法public static Account getAccountByStatic(){return new Account();}
}
@Test
public void testFactory(){//静态工厂创建对象Account account1 = AccountFactory.getAccountByStatic();//实例工厂创建对象AccountFactory accountFactory = new AccountFactory();Account account2 = accountFactory.getAccount();
}
Spring实现bean的创建
普通方式
<!--这种方式等同于直接new对象(底层使用反射创建-newInstance())-->
<bean id="accountDao" class="com.itheima.ioc.dao.impl.AccountDaoImpl"></bean>
静态工厂
<!--
class: 工厂类全路径
factory-method: 工厂类中的静态方法
-->
<bean id="account1" class="com.itheima.ioc.factory.AccountFactory" factory-method="getAccountByStatic"></bean>
测试:
@Test
public void testSpringStaticFactory(){ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");Account account1 = (Account) applicationContext.getBean("account1");System.out.println(account1);
}
实例工厂
<!--工厂对象-->
<bean id="accountFactory" class="com.itheima.ioc.factory.AccountFactory"></bean>
<!--factory-bean: 指定工厂实例factory-method: 指定工厂中的非静态方法
-->
<bean id="account2" factory-bean="accountFactory" factory-method="getAccount"></bean>
测试
@Test
public void testSpringFactory(){ApplicationContext applicationContext =new ClassPathXmlApplicationContext("applicationContext.xml");Account account2 = (Account) applicationContext.getBean("account2");System.out.println(account2);
}
更多推荐
Spring实现bean的创建(静态工厂)
发布评论