控制反转IOC是说创建对象的控制权进行转移,以前创建对象的主动权和创建时机是由自己把控的,而现在这种权力转移到第三方,比如转移交给了IOC容器,把创建对象的任务交给spring框架来完成
基础代码示意
package com;
import dao.AccountDaoImp;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import util.MyBeanFactory;
public class test {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//获取核心容器
//饿汉模式 适用于单例模式
ApplicationContext ac= new ClassPathXmlApplicationContext("bean.xml");
//根据id获取bean对象
AccountDaoImp ad= (AccountDaoImp) ac.getBean("myName");
System.out.println(ad);
// 懒汉模式 适用于多例模式
Resource resource=new ClassPathResource("bean.xml");
BeanFactory beanFactory=new XmlBeanFactory(resource);
AccountDaoImp ad2= (AccountDaoImp) beanFactory.getBean("myName");
}
}
package dao;
public class AccountDaoImp implements IAccountDao{
@Override
public void say() {
System.out.println("俺是工厂模式得模拟");
}
}
<?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">
<bean id="myName" class="dao.AccountDaoImp"/>
</beans>