需要用到的几个类:
1.IUserService :
public interface IUserService {
public void add();
}
2.UserServiceImpl:
public class UserServiceImpl implements IUserService{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void add() {
System.out.println("创建用户...." + name);
}
}
3.beans.xml 文件配置
<?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 id="userService" class="com.lkp.service.UserServiceImpl">
<property name="name" value="summer"></property>
</bean>
</beans>
4.Spring 容器加载的三种方式
第一种:ClassPathXmlApplicationContext ClassPath类路径加载:指的就是classes路径(常用)
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
IUserService userService = (IUserService) context.getBean("userService");
userService.add();
}
第二种:文件系统路径获得配置文件
public void test1() {
ApplicationContext context = new FileSystemXmlApplicationContext("/src/beans.xml");
IUserService userService = (IUserService) context.getBean("userService");
userService.add();
}
第三种:使用BeanFactory
public void test1() {
String path = "/src/beans.xml";
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(path));
IUserService userService = (IUserService) factory.getBean("userService");
userService.add();
}
5.BeanFactory和ApplicationContext对比
- BeanFactory 采取延迟加载,第一次getBean时才会初始化Bean
- ApplicationContext是对BeanFactory扩展,提供了更多功能
- 国际化处理
- 事件传递
- Bean自动装配
- 各种不同应用层的Context实现
6.如何配置一个bean【对象】
spring内部创建对象原理:
- 解析xml文件,获取类名,id,属性
- 通过反射,用类型创建对象
- 给创建的对象赋值