spring中的ioc

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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--把对象的创建交给spring来管理-->
<!--id:获取是的唯一标志,class:反射要创建的权限定类名-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
</beans>

spring ioc容器的获取:
/**
* 模拟一个表现层,用于调用业务层
*/
public class Client {
/*
* 获取spring容器的ioc核心容器,并根据id获取对象
* ApplicationContext的三个常用实现类:
* ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径下,不在的话,加载不了
    *   FileSystemXmlApplicationContext:它可以加载磁盘任意路径下的配置文件(必须有访问权限)
    *   AnnotationConfigApplicationContext:它是用于读取注解创建容器的
    *   核心容器的两个接口引发出的问题:
* ApplicationContext:单例对象适用 采用此接口
* 它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说只要一读取完配置文件马上就创建配置文件中配置的对象。
* BeanFactory: 多例对象适用
* 它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式。也就是什么时候根据id获取对象了,什么时候才真正的创建对象。
* */
public static void main(String[] args) {
// 1. 获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// ApplicationContext ac = new FileSystemXmlApplicationContext("D:\IdeaProjects\day01_eesy_03spring\src\main\resources\bean.xml");
// 2. 根据id获取Bean对象
IAccountService as = (IAccountService)ac.getBean("accountService");
IAccountDao adao = ac.getBean("accountDao", IAccountDao.class);
System.out.println(as);
System.out.println(adao);


}
}
原文地址:https://www.cnblogs.com/kingchen/p/12961241.html