总述:
- 导包
- 配置
- 测试
(一)导包:相当于创建一个容器所需要的包
注意:一定要配置路径
(二)配置
- 创建一个组件(类):
代码:
package com.atguigu.bean;
public class Person {
private String lastName;
private Integer age;
private String gender;
private String email;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Person [lastName=" + lastName + ", age=" + age + ", gender=" + gender + ", email=" + email + "]";
}
}
2.将组件(类)配置到容器中(ioc在scr目录下)
代码:
<?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注册一个组件***
<bean id="person01" class="com.atguigu.bean.Person">
<property name="age" value="18"></property>
<property name="email" value="com.atguigu@qq.com"></property>
<property name="gender" value="男"></property>
<property name="lastName" value="张三"></property>
</bean>
</beans>
(三)测试
- 创建一个测试类
代码:
package com.atguigu.test;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.atguigu.bean.Person;
public class iocTest {
@Test
public void test() {
//新建一个容器
ApplicationContext ioc = new ClassPathXmlApplicationContext("ioc.xml");
Person bean = (Person) ioc.getBean("person01");
System.out.println(bean);
}
}
结果: