【SpringIOC】Spring基于xml解决程序间的耦合
引言
Spring的Ioc容器,用于解决程序之间的耦合,通过配置文件和反射获取对象。(工厂模式思想)
框架自带工厂模式
配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountService" class="com.czy.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.czy.dao.impl.AccountDaoImpl"></bean>
</beans>
通过配置文件与映射获取对象(单例对象)
package com.czy.ui;
import com.czy.service.AccountService;
import com.czy.service.impl.AccountServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 模拟保存账户
*/
public class Client {
/**
* 获取spring的Ioc核心容器,并根据id获取对象
* @param args
*/
public static void main(String[] args){
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取bean对象
AccountService service0 = ac.getBean("accountService",AccountService.class);
AccountService service = (AccountService)ac.getBean("accountService");
System.out.println(service0);
System.out.println(service);
}
}
单例对象:
Application三个常用实现类(BeanFactory)
1.ClassPathXmlApplicationContext
它可以加载类路径下的配置文件,要求配置文件必须在类路径下。不在的话,加载不了(maven工程里的resources)
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取bean对象
AccountService service0 = ac.getBean("accountService",AccountService.class);
AccountService service = (AccountService)ac.getBean("accountService");
2.FileSystemXmlApplicationContext
它可以加载磁盘任意路径下的配置文件(必须有访问权限)
//1.获取核心容器对象
ApplicationContext ac = new FileSystemXmlApplicationContext("E:\\JAVA\\Spring\\day01_eesy_02Spring\\src\\main\\resources\\bean.xml");
//2.根据id获取bean对象
AccountService service0 = ac.getBean("accountService",AccountService.class);
AccountService service = (AccountService)ac.getBean("accountService");
3.AnnotationConfigApplicationContext
它用于读取注解创建容器的。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!