<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 把对象的创建交给Spring来管理 -->
<!-- spring对bean的管理细节
1.创建bean的三种方式
2.bean对象的作用范围
3.bean对象的生命周期
-->
<!-- 创建Bean的三种方式 -->
<!-- 第一种方式:使用默认构造函数创建。
在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时。
采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建。
<bean id="accountService" class="com.lwb.service.impl.AccountServiceImpl"></bean>
-->
<!-- 第二种方式:使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
<bean id="instanceFactory" class="com.lwb.factory.InstanceFactory"></bean>
<bean id="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
-->
<!-- 第三种方式:使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器) -->
<bean id="accountService" class="com.lwb.factory.StaticFactory" factory-method="getAccountService"></bean>
</beans>
package com.lwb.service.impl;
import com.lwb.service.IAccountService;
public class AccountServiceImpl implements IAccountService {
public void saveAccount() {
System.out.println("service中的saveAccount方法执行了");
}
}
package com.lwb.factory;
import com.lwb.service.IAccountService;
import com.lwb.service.impl.AccountServiceImpl;
public class InstanceFactory {
public IAccountService getAccountService(){
return new AccountServiceImpl();
}
}
package com.lwb.factory;
import com.lwb.service.IAccountService;
import com.lwb.service.impl.AccountServiceImpl;
public class StaticFactory {
public static IAccountService getAccountService(){
return new AccountServiceImpl();
}
}