多学习。

【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

它用于读取注解创建容器的。

posted @   czyaaa  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示