1.导包;
四个容器所需的包,一个日志包
注意:Spring运行的时候依赖一个日志包:commons-logging-1.1.3.jar,没有就会报错
2.写配置
Spring的配置文件中,集合了 Spring的ioc容器管理的所有组件(会员清单);
创建一个Spring Bean Configuration File(Spring的bean配置文件)
3.测试
先创建一个类
package Test;
public class Person {
private String name;
private int age;
private String grade;
private String email;
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", grade=" + grade + ", email=" + email + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
在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">
<!-- 注册一个Person对象,Spring会自动创建这个Person对象 -->
<!-- 一个bean标签注册一个组件
class:写要注册的组件的全类名(包名加类名)
id:这个对象的唯一标识
-->
<bean class="Test.Person" id="person01">
<!-- 使用property为这个对象的属性赋值 name为属性名,value为属性值 -->
<property name="name" value="张三"></property>
<property name="age" value="12"></property>
<property name="grade" value="四"></property>
<property name="email" value="123456789@qq.com"></property>
</bean>
</beans>
新建一个Test测试
package Test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class IOC {
@Test
public void test() {
//ApplicationContext:代表容器
//ClassPathXmlApplicationContext:代表当前应用的xml配置文件在classpath下
//根据spring的配置未见得到ioc容器对象
//ioc后面的参数写xml文件的名字
ApplicationContext ioc=new ClassPathXmlApplicationContext("IOC.xml");
Person person=(Person)ioc.getBean("person01");
System.out.println(person);
}
}
可能存在的问题
1.所有的源码包里面的东西都会合并到一起放在类路径里(bin)
1.1:java:/bin/
1.2:web:/WEB-INF/classes/
2.导包:日志包不能忘
3.先导包后创建配置文件(bean)
4.当类的图标右上角出现s标志着容器接管了该类
细节
1.ApplicationContext(IOC容器的接口)
new ClassPathXmlApplicationContext("ioc.xml");代表IOC容日的配置 文件在类路径下;
new FileSystemXmlApplicationContext("F://IOC.xml");代表IOC容器的配置文件在磁盘路径下;
2.容器中对象的创建在创建容器的时候就已经创建了
3.同一个组件在容器中是单实例的,即获取N次获取的都是同一个对象
No bean named 'xxx' is defined
5.property赋值是用set方法来赋值
6.javaBean的属性名是由getter/setter方法来决定,推荐所有的getter、setter方法都用自动生成