- //bean.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">
- <!-- 把对象的创建交给 spring 管理 -->
- <bean id="accountService" class="com.hope.service.impl.AccountServiceImpl"/>
- <bean id="accountDao" class="com.hope.dao.impl.AccountDaoImpl"/>
- </beans>
- package com.hope.ui;
- import com.hope.dao.IAccountDao;
- import com.hope.service.IAccountService;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- /**
- * @author newcityman
- * @date 2019/11/18 - 14:23
- * 模拟一个表现层框架
- */
- public class Client {
- /**
- * 获取 spring 的 IoC 容器, 根据 id 获取对象
- * ApplicationContext 接口的三个实现类
- * 1,ClassPathXmlApplicationContext: 它可以加载类路径下的配置文件, 要求配置文件必须在类路径下面. 不在的话, 无法加载
- * 2,FileSystemXmlApplicationContext: 它可以加载磁盘任意路径下的配置文件 (必须有访问权限)
- * 3,AnnotationConfigApplicationContext: 它是读取注解创建容器的方法
- * @param args
- */
- public static void main(String[] args) {
- //1, 获取核心容器对象
- ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
- //2, 根据 id 获取 bean 对象
- IAccountService as=(IAccountService)ac.getBean("accountService");
- IAccountDao ad = ac.getBean("accountDao",IAccountDao.class);
- System.out.println(as);
- System.out.println(ad);
- }
- }
来源: http://www.bubuko.com/infodetail-3294298.html