创立maven项目后配置pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>day_03</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
</dependencies>
</project>
获取spring的Ioc核心容器,并根据id获取对象 * ApplicationContext的三个常用实现类: * ClassPathXmlApplicationContext:可以加载类路径下的配置文件 * FileSystemXmlApplicationContext:可以加载磁盘任意路径下的配置文件(必须有配置文件) * AnnotationConfigApplicationContext:可以用于读取注解创建容器 * * 核心容器的两个接口引发的问题 * ApplicationContext: 单例对象适用 采用此接口定义容器对象 * 它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象 * BeanFactory: 多例对象适用 * 它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象 *
public class Client {
public static void main(String[] args) {
//1.获取核心容器对象
//ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");//此时创建对象
//ApplicationContext ac = new FileSystemXmlApplicationContext("C:\\Users\\12469\\Desktop\\java-OOP\\day_03\\src\\main\\resources\\bean.xml");
//2.根据id获取Bean对象
//IAccountService as = (IAccountService)ac.getBean("accountService");
//IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
//as.saveAccount();
//System.out.println(as);
//System.out.println(adao);
//-------------------BeanFactory-------------
Resource resource = new ClassPathResource("bean.xml");
BeanFactory factory = new XmlBeanFactory(resource);
IAccountService as = (IAccountService)factory.getBean("accountService");//此时创建对象
IAccountDao adao = factory.getBean("accountDao",IAccountDao.class);
}
}
resources中 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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountService" class = "com.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.dao.impl.AccountDaoImpl"></bean>
</beans>
<bean id="" class="" ></bean>用于写出需要创建的类的信息,id为类名,class为类型