当前页面: 开发资料首页 → Spring 专题 → 快速上手Spring--11. 自动绑定和依赖检查
摘要: 快速上手Spring--11. 自动绑定和依赖检查 这篇文章来谈谈 《Spring Framework 开发参考手册》 的3.3.5小节中的“自动装配协作对象”和3.3.6 小节中的“依赖检查”。 仔...
HelloBean.java |
package javamxj.spring.basic.autowiring;
public class HelloBean { private String hello; public String getHello() { return hello; } public void setHello(String hello) { this.hello = hello; } } |
HelloDate.java |
package javamxj.spring.basic.autowiring;
import java.util.Date; import java.util.GregorianCalendar; public class HelloDate { public HelloDate() { System.out.println("defalt Constructor called"); } public HelloDate(HelloBean hello) { System.out.println("HelloDate(HelloBean) called"); } public HelloDate(HelloBean hello, Date date) { System.out.println("HelloDate(HelloBean,Date) called"); } public void setHello(HelloBean hello) { System.out.println("Property hello set"); } public void setDate(Date date) { System.out.println("Property date set"); } public void setDate2(GregorianCalendar date) { System.out.println("Property date2 set"); } } |
beans.xml |
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="date" name="myDate" class="java.util.Date"/>
<bean id="helloBean" class="javamxj.spring.basic.autowiring.HelloBean"
dependency-check="simple">
<property name="hello" value="javamxj"/>
</bean>
<bean id="HelloByName" class="javamxj.spring.basic.autowiring.HelloDate"
autowire="byName"/>
<bean id="HelloByType" class="javamxj.spring.basic.autowiring.HelloDate"
autowire="byType"/>
<bean id="HelloConstructor" class="javamxj.spring.basic.autowiring.HelloDate"
autowire="constructor"/>
<bean id="HelloAutodetect" class="javamxj.spring.basic.autowiring.HelloDate"
autowire="autodetect"/>
<bean id="helloCheck" class="javamxj.spring.basic.autowiring.HelloDate" autowire="byType"
dependency-check="objects">
<property name="date2" >
<bean class="java.util.GregorianCalendar"/>
</property>
<!-- <property name="date" ref="date"/>-->
<!-- <property name="hello" ref="helloBean"/>-->
</bean>
</beans>
Main.java |
package javamxj.spring.basic.autowiring; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main { public static void main(String[] args) { BeanFactory bf = new XmlBeanFactory(new ClassPathResource( "javamxj/spring/basic/autowiring/beans.xml")); System.out.println("使用 byName:"); HelloDate hb = (HelloDate) bf.getBean("HelloByName"); System.out.println("\n使用 byType:"); hb = (HelloDate) bf.getBean("HelloByType"); System.out.println("\n使用 constructor:"); hb = (HelloDate) bf.getBean("HelloConstructor"); System.out.println("\n使用 autodetect:"); hb = (HelloDate) bf.getBean("HelloAutodetect"); System.out.println("\n使用 dependency-check:"); hb = (HelloDate) bf.getBean("helloCheck"); } } |