一、创建bean的三种方式
1、采用默认的构造函数创建bean对象,如果没有默认的构造函数,则对象无法创建
<bean id=" accountService" class="com.xxx.service.impl.AccountServiceImpl"></bean>
AccountServiceImpl中的代码:
ublic class AccountServiceImpl implements IAccountService {
public AccountServiceImpl()
{
System.out.println("已经创建完成了");
}
}
2、声明工厂
<bean id = "instanceFactory" class="com.xxx.factory.InstanceFactory"></bean>
<bean id ="accountService" factory-bean="instanceFactory" factory-method="getAccountService"></bean>
工厂里的内容:
public class InstanceFactory {
public IAccountService getAccountService(){
return new AccountServiceImpl();
}
}
3、使用静态工厂中的静态方法创建对象
<bean id ="accountService" class="com.xxx.factory.StaticFactory" factory-method="getAccountService"></bean>
静态工厂:
public class StaticFactory {
public static IAccountService getAccountService(){
return new AccountServiceImpl();
}
}
入口函数:
public class Client {
/**
* 获取spring的Ioc核心容器,并根据id获取对象
*
* ApplicationContext的三个常用实现类
* ClassPathXmlApplicationContext :它可以加载类路径下的配置文件,要求配置文件必须在类路
径下,不在的话,加载不了(更常用)
* FileSystemXmlApplicationContext:它可以加载磁盘任意路径下的配置文件,必须要有访问权限
* AnnotationConfigAppliContext:它是用于读取主机创建容器的
*
*/
public static void main(String[] args) {
//1、获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// ApplicationContext ac = new FileSystemXmlApplicationContext("bean.xml文件在磁盘中的路径");
//2、根据id获取Bean对象
IAccountService as =(IAccountService) ac.getBean("accountService");
}
}
二、bean标签的scope属性
//当一个bean的作用域设置为singleton, 那么Spring IOC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例
//当为prototype的时候,则不会返回同一个实例。
<bean id = "accountService" class="com.xxx.service.impl.AccountServiceImpl" scope="prototype"></bean>