加载Spring容器的方式有三种,具体哪三种 我们一一来介绍
第一种:ClassPath类路径:指的就是classes路径(最常用)
ApplicationContext context=new ClassPathXmlApplicationContext("applicaiontContext.xml");
如果把XML放在src下 就直接写XML名字即可 如果放到包下 那就是包名+配置xml名字 例如com/ls/applicaiont.xml
第二种:文件系统路径获得配置文件【绝对路径】
ApplicationContext context=new FileSystemXmlApplicationContext("C:\Users\kis\Desktop\spring01\src\com.......");
第三种:使用BeanFactory(了解)
String path="C:\Users\kis\Desktop\spring01\src\com........";
BeanFactory factory=new XmlBeanFactory(new FileSystemResource(path));
<?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.xsd">
<!-- 配置一个bean【对象】 class 类的路径 -->
<bean id="userService" class="com.lq.service.impl.UserServiceImpl">
<!--依赖注入数据 调用属性的set方法 -->
<property name="name" value="zhangsan"></property>
</bean>
</beans>
Spring 内部创建对象的原理:
1.解析XML文件,获取类名、id、(相当于XML中bean id class) 属性(相当于XML中property)
2. 通过反射,用类名字创建一个对象
3.给创建的对象进行赋值(依赖注入) (相当于XML中value)
- BeanFactory 采取延迟加载,第一次getBean时才会初始化Bean
- ApplictionContext即时加载
- ApplicationContext是对BeanFactory扩展,提供了更多功能
- 国际化处理
- 事件传递
- Bean装配
- 各种不同应用层的Context实现
二、装配Bean的三种方式讲解
Service:
public class UserServiceImpl implements UserService{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void add() {
System.out.println("创建用户..."+name);
}
}
public class UserServiceFactory1 {
public static UserService createService() {
return new UserServiceImpl();
}
}
public class UserServiceFactory2 {
public UserService createUserService() {
return new UserServiceImpl();
}
}
<!--第一种方式:new 实现类 使用构造方法实例化-->
<bean id="userService" class="com.lq.service.impl.UserServiceImpl">
<!--依赖注入数据 调用属性的set方法 -->
<property name="name" value="zhangsan"></property>
</bean>
<!--第二种方式:通过静态工厂方法-->
<bean id="userService2" class="com.lq.service.impl.UserServiceFactory1" factory-method="createService">
<property name="name" value="zhangsan"></property>
</bean>
<!--第三种方式:通过实例工厂方法-->
<bean id="factory" class="com.lq.service.impl.UserServiceFactory2"></bean>
<bean id="userSerice3" factory-bean="factory2" factory-method="createUserService"></bean>
</beans>
Test主方法
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService1= (UserService)context.getBean("userService");
UserService userService2= (UserService)context.getBean("userService2");
UserService userService3= (UserService)context.getBean("userService3");
userService1.add();
三、Bean的作用域
这里只展示两个常用的 还有三个不常用的分别是(request、session、globalSession)
类别 | 说明 |
Singleton(单例) | 在Spring IOC容器中仅存在一个Bean实例,Bean以单例方式存在,默认值为单例 |
Prototype(多例) | 每次从容器中调用Bean时,都返回一个新的实例,即每次调用getBean()时,相当于执行new xxxBean() |
在xml中示例为:
<bean id="userService" class="com.lq.service.impl.UserServiceImpl" scope="prototype"></bean>