首先建项目,可参考 https://blog.csdn.net/2303_79008526/article/details/141141114?spm=1001.2014.3001.5502
一、spring 环境搭建
(一)导相关坐标
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>spring_ioc_003</artifactId>
<version>1.0-SNAPSHOT</version>
<!-- 添加坐标 -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.28</version>
</dependency>
</dependencies>
</project>
(二)搭建配置文件
我起名为 beans
(三)建包建类,写方法
package com.apesource.pojo;
public class Student {
}
package com.apesource.dao;
public interface IDao {
public void save();
}
package com.apesource.dao;
public class DaoImp implements IDao{
@Override
public void save() {
System.out.println("======Dao的新增方法======");
}
}
package com.apesource.test;
public class Test01 {
}
(四)找到需要以解耦方式获取实例的类,将需要spring管理的类注入spring容器
语法:<bean id="唯一标识" class="类"></bean>
<?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">
<!-- 注入类 -->
<!-- id起名随意 -->
<bean id="student" class="com.apesource.pojo.Student"></bean>
<bean id="daoImp" class="com.apesource.dao.DaoImp"></bean>
</beans>
(五)向spring容器中索取java实例(解耦)
3.1.加载spring核心配置文件,获取spring容器对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
3.2.获取对象,测试运行
Student student = (Student)applicationContext.getBean("student");
package com.apesource.test;
import com.apesource.dao.DaoImp;
import com.apesource.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test01 {
public static void main(String[] args) {
//1.加载spring核心配置文件,获取spring容器对象
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("beans.xml");
//2.获取对象(getBean(" beans.xml 文件注入类时的 id 名"))
Student student = (Student) applicationContext.getBean("student");
System.out.println(student);
DaoImp dao = (DaoImp) applicationContext.getBean("daoImp");
dao.save();
}
}
结果如下,运行成功
二、小结
模拟三层--控制层、业务层和数据访问层 (yuque.com),与它的 perproties 对比理解
beans.properties
beans.xml
key=values
id=class
BeansFactory
ApplicationContext
getBean(key)
getBean(id)
关键字:
BeanFactory(父)
ApplicationContext(子《孙子》)
ClassPathXmlApplicationContext==>通过加载主配置文件的相对路径,获取spring容器
FileSystemXmlApplicationContext==>通过加载主配置文件的绝对路径,获取spring容器
AnnotationConfigApplicationContext==>加载配置类,获取spring容器