一、直接创建bean
<bean id="accountserviceimpl" class="com.itheima.service.impl.AccountServiceImpl" ></bean>
此种方式是: 两个标签分别是id(根据这个唯一标识,能够找到此bean)class(所对应的类的全名称)
二、spring管理静态工厂-使用静态工厂的方法创建对象
public class StaticFactory { public static IAccountService createAccountService(){ return new AccountServiceImpl(); } }
<bean id="accountService" class="com.itheima.factory.StaticFactory" factory-method="createAccountService"></bean>
此种方式是: 使用 StaticFactory 类中的静态方法 createAccountService 创建对象,并存入 spring 容器 id 属性:指定 bean 的 id,用于从容器中获取 class 属性:指定静态工厂的全限定类名 factory-method 属性:指定生产对象的静态方法
三、spring管理实例工厂-使用实例工厂的方法创建对
public class InstanceFactory { public IAccountService createAccountService(){ return new AccountServiceImpl(); } }
<bean id="instancFactory" class="com.itheima.factory.InstanceFactory"></bean> <bean id="accountService" factory-bean="instancFactory" factory-method="createAccountService"></bean>
此种方式是: 先把工厂的创建交给 spring 来管理。 然后在使用工厂的 bean 来调用里面的方法 factory-bean 属性:用于指定实例工厂 bean 的 id。 factory-method 属性:用于指定实例工厂中创建对象的方法。