JAVA全系列 教程
3762个小节阅读:7092.1k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
接下来我们使用Spring实现IOC,Spring内部也有一个容器用来管理对象。
创建Maven工程,引入依赖
xxxxxxxxxx
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
创建POJO类、Dao类和接口
xxxxxxxxxx
public class Student {
private int id;
private String name;
private String address;
// 省略getter/setter/构造方法/tostring
}
public interface StudentDao {
// 根据id查询学生
Student findById(int id);
}
public class StudentDaoImpl implements StudentDao{
@Override
public Student findById(int id) {
// 模拟从数据库查找出学生
return new Student(1,"百战程序员","北京");
}
}
编写xml配置文件,配置文件中配置需要Spring帮我们创建的对象。
xxxxxxxxxx
<?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="studentDao" class="com.itbaizhan.dao.StudentDaoImpl"></bean>
</beans>
测试从Spring容器中获取对象。
xxxxxxxxxx
public class TestContainer {
@Test
public void t1(){
// 创建Spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// 从容器获取对象
StudentDao studentDao1 = (StudentDao) ac.getBean("studentDao");
StudentDao studentDao2 = (StudentDao) ac.getBean("studentDao");
System.out.println(studentDao1.hashCode());
System.out.println(studentDao2.hashCode());
System.out.println(studentDao1.findById(1));
}
}
1. Spring配置文件中,通过配置标签配置容器中的对象
A <beans>
B <pojo>
C <entity>
D <bean>
2. Spring配置文件中,<bean>
标签的属性可以配置对象类型
A id
B name
C class
D value
1=>D 2=>C