spring5.0学习笔记2

本文详细介绍Spring框架的IOC(Inverse of Control)概念,展示如何使用XML配置文件搭建IOC环境,以及通过ClassPathXmlApplicationContext加载配置文件,创建并管理AccountService和AccountDao对象的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IOC Inverse of Control
把创建对象的控制权交给工厂

Spring基于XML的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"
		xmlns:context="http://www.springframework.org/schema/context"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">	
<!-- 把创建对象交给spring管理 -->				
<bean id="accountServerice" class="com.test.AccountServiceImp"></bean>
<bean id="accountDao" class="com.test.AccountDaoImp"></bean>
</beans>
/**
 * ioc
 */
package com.test;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 模拟一个表现层,用户调用业务层
 * @author Administrator
 *
 */
  /**
   * 获取spring的IOC核心容器
   * ApplicationContext的三个常用实现类
   * 	ClassPathXmlApplicationContext:可以加载类路径下的配置文件  常用
   * 	FileSystemXmlApplicationContext:加载任意磁盘下的配置文件,必须有访问权限
   * 	AnnotationConfigApplicationContext:用于读取注解创建容器的
   */
public class Test{
    public static void main(String[] args){
    	//1.获取核心容器对象
    	ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
    	//2.根据id获取bean对象
    	IAccountService as = (IAccountService)ac.getBean("accountServerice");
    	IAccountDao adao = (IAccountDao)ac.getBean("accountDao");
    	System.out.println(as);
    	System.out.println(adao);
    }
}
/**
 * 创建bean对象的工厂
 * Bean 在计算机术语中,含义为可重用组件
 * JavaBean,用java语言编写的可重用组件
 * 		JavaBean >实体类
 * 		具体到项目中,就是service和dao对象
 * 		第一个:配置一个文件来配置service和dao,配置的内容是唯一标识的权限定内名
 * 		第二个:通过读取配置文件内容,反射创建对象
 * 
 * 		配置文件可以是propertie也可以使xml
 */
class BeanFactory{
	private static Properties props;
	//定义个Map,用于存放创建的对象,称之为容器
	private static Map<String, Object> beans;
	static{
		try {
			//实例化对象
			props=new Properties();
			//InputStream in=new FileInputStream();
			//获取properties文件的流对象
			InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
			props.load(in);
			//实例化容器
			beans = new HashMap<String, Object>();
			//取出配置文件中所有的key
			Enumeration<Object> keys = props.keys();
			//遍历枚举
			while(keys.hasMoreElements()){
				//取出key
				String key = keys.nextElement().toString();
				//根据key获取value
				String beanPath = props.getProperty(key);
				//反射创建对象
				Object value = Class.forName(beanPath).newInstance();
				//把key-value存入容器中
				beans.put(key, value);
			}
		} catch (Exception e) {
			// TODO: handle exception
			throw new ExceptionInInitializerError("初始化properties失败");
		}
	}
	/**
	 * 根据bean名称获取bean对象,单例
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName){
		return beans.get(beanName);
	}
	/*
	public static Object getBean(String beanName){
		Object bean = null;
		try {
			String beanPath=props.getProperty(beanName);
			System.out.println(beanPath);
			bean=Class.forName(beanPath).newInstance();//每次都会调用默认构造函数创建对象
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return bean;
	}
	*/
}
interface IAccountService{
	/**
	 * 模拟保存账户
	 */
	 void saveAccount();
}

/**
 * 业务层实现类
 */
class AccountServiceImp implements IAccountService{
	//private IAccountDao accountDao=new AccountDaoImp();
	private IAccountDao accountDao = (IAccountDao)BeanFactory.getBean("accountDao");
	private int i=1;
	public void saveAccount(){
		System.out.println(accountDao);
		accountDao.saveAccount();
		System.out.println(i);
		i++;
	}
}
/**
 * 账户的持久层接口
 */
interface IAccountDao{
	/**
	 * 模拟保存账户
	 */
	 void saveAccount();
}

/*
 * 账户的持久层实现类,若没有编译器也不会报错
 */
class AccountDaoImp implements IAccountDao{
	public void saveAccount(){
		System.out.println("保存了账户");
	}
}

2020-3-24 21:21:17 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1ef9f1d: display name [org.springframework.context.support.ClassPathXmlApplicationContext@1ef9f1d]; startup date [Tue Mar 24 21:21:17 CST 2020]; root of context hierarchy
2020-3-24 21:21:17 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [bean.xml]
2020-3-24 21:21:18 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@1ef9f1d]: org.springframework.beans.factory.support.DefaultListableBeanFactory@1175422
2020-3-24 21:21:18 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1175422: defining beans [accountServerice,accountDao]; root of factory hierarchy
com.test.AccountServiceImp@1d6f122
com.test.AccountDaoImp@7109c4
com.test.AccountDaoImp@1385660
保存了账户


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值