2.bean.xml文件编写:org.springframework spring-context5.3.20
获取文件头:Core Technologies
访问官网路径进行复制,这里已经帮你整理好了
文件全部内容:
3.两者不同方式读取bean.xml文件进行获取bean对象:
public class Client {
* 核心容器的接口引发出的问题:
* ApplicationContext: 单例对象适用 (常用)
* 它在创建容器时,创建对象采取的策略是采用立即加载的方式,也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象。
* BeanFactory: 多例对象适用
* 它在创建容器时,创建对象采取的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什么时候才真正的创建对象。
public static void main(String[] args) {
//第一种加载方式:加载类任意路径下的配置文件
System.out.println("第一种加载方式:加载类任意路径下的配置文件");
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("E:\Demo\demo02\demo01\src\main\resources\bean.xml");
//根据id获取Bean对象
AccountDao accountDao = (AccountDao) applicationContext.getBean("AccountDao");
// //.class获取AccountDao对象
AccountDao accountDaoClass = applicationContext.getBean("AccountDao", AccountDao.class);
IAccountService iAccountService = (IAccountService) applicationContext.getBean("IAccountService");
System.out.println("AccountDao=" + accountDao + "n" + "IAccountService=" + iAccountService + "n" + "accountDaoClass=" + accountDaoClass);
System.out.println("第二种加载方式:加载类路径下的配置文件");
//第二种加载方式:加载类路径下的配置文件
ApplicationContext applicationContext1 = new ClassPathXmlApplicationContext("bean.xml");
//根据id获取Bean对象
AccountDao accountDao1 = (AccountDao) applicationContext1.getBean("AccountDao");
IAccountService iAccountService1 = (IAccountService) applicationContext.getBean("IAccountService");
//.class获取IAccountService对象
IAccountService IAccountServiceClass = applicationContext1.getBean("IAccountService", IAccountService.class);
System.out.println("AccountDao1=" + accountDao1 + "n" + "iAccountService1=" + iAccountService1 + "n" + "IAccountServiceClass=" + IAccountServiceClass);
System.out.println("--------------BeanFactory----------------");
Resource resource = new ClassPathResource("bean.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
IAccountService iAccountService = (IAccountService) beanFactory.getBean("IAccountService");
System.out.println(iAccountService);
}
}
到这里bean.xml文件装配bean获取对象到此完成,看看运行结果:



