Spring IOC所需要的基本包
创建学生类
package com.ctguyxr.spring5.entity;
/**
* Created By Intellij IDEA
*
* @author Xinrui Yu
* @date 2021/12/7 16:27 星期二
*/
public class Student {
private String name = "学生";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void say(){
System.out.println("学生会说话");
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
}
编写xml文件
注意:
- xml文件的路径最好是直接写在 项目 / 模块的 src 路径下
- 如果成功的引入了依赖那么我们是可以直接创建配置 spring的 xml 文件的,如下图
在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="student" class="com.ctguyxr.spring5.entity.Student"/>
</beans>
测试
编写测试类,使用Spring来创建对象
package com.ctguyxr.spring5.test;
import com.ctguyxr.spring5.entity.Student;
import org.junit.Test;
import org.springframework.context.*;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created By Intellij IDEA
*
* @author Xinrui Yu
* @date 2021/12/7 16:40 星期二
*/
public class Spring5Test {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
Student student = context.getBean("student", Student.class);
student.say();
System.out.println(student.getName());
System.out.println(student);
}
}