定义两个bean分别为Bean1和Bean2
Bean1.java
package com.blog.ytso.com.bean; public class Bean1 { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Bean2.java
package com.blog.ytso.com.bean; public class Bean2 { private String name; private String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
applicationContext.xml配置文件
把Bean1和Bean2配置到xml文件中
<bean id="bean1" class="com.blog.ytso.com.bean.Bean1">
<property name="name" value="zhangsan" />
<property name="age" value="21" />
</bean>
<!-- 此处的class路径是错误的,没有Bean3这个类 -->
<bean id="bean2" class="com.blog.ytso.com.bean.Bean3">
<property name="name" value="lisi" />
<property name="sex" value="男" />
</bean>
进行测试
使用XmlBeanFactory
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub XmlBeanFactory factory = new XmlBeanFactory(new FileSystemResource("src/applicationContext.xml")); Bean1 bean1 = (Bean1)factory.getBean("bean1"); System.out.println("bean1.name: "+bean1.getName()); System.out.println("bean1.age: "+bean1.getAge()); } }
观察结果 可以运行通过
接下来使用ApplicationContext
public class Client { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Bean1 bean1 = (Bean1)context.getBean("bean1"); System.out.println("bean1.name: "+bean1.getName()); System.out.println("bean1.age: "+bean1.getAge()); } }
结果报异常
Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.blog.ytso.com.bean.Bean3] for bean with name 'bean2' defined in class path resource
[applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: com.blog.ytso.com.bean.Bean3
我们在applicationContext.xml中配置了两个Bean,bean1和bean2 虽然bean2中找不到Bean3这个类,但我们getBean()的时候也没有用到bean2啊,为什么会报错呢?
原因是ApplicationContext和BeanFactory提供了不同的加载机制,ApplicationContext和BeanFacotry相比,提供了更多的扩展功能,但其主要区别在于后者是延迟加载,如果Bean的某一个属性没有注入,BeanFacotry加载后,直至第一次使用调用getBean方法才会抛出异常;而ApplicationContext则在初始化自身时检验,这样有利于检查所依赖属性是否注入;所以通常情况下我们选择使用ApplicationContext.
解决延迟加载的办法是在applicationContext.xml中<beans>标签中添加default-lazy-init=”true”属性
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd" default-lazy-init="true">
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/14413.html