Java Spring Tutorial -- autowire byName, byType, constructor

文件结构:

Java Spring Tutorial -- autowire byName, byType, constructor_第1张图片



package com.zxl.spring;

public class MessageBean {
	private RefMessageBean refMessageBean;
	/* bean & constructor */
	/*public MessageBean(RefMessageBean refMessageBean){
		this.refMessageBean=refMessageBean;
	}*/
	public void setRefMessageBean(RefMessageBean refMessageBean){
		this.refMessageBean=refMessageBean;
	}
	public RefMessageBean getRefMessageBean(){
		return refMessageBean;
	}
}

package com.zxl.spring;

public class RefMessageBean {
	private String message;
	public RefMessageBean(String message){
		this.message=message;
	}
	public String getMessage(){
		return message;
	}
}

package com.zxl.spring;


import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApp09 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("SpringBeans.xml");
		MessageBean messageBean =(MessageBean) context.getBean("messageBean");
		System.out.println(messageBean.getRefMessageBean().getMessage());
		context.close();
	}

}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<!-- bean -->
	 <!-- <bean id="messageBean" class="com.zxl.spring.MessageBean" >
	    <constructor-arg ref="refMessageBean" />
	</bean>
	<bean id="refMessageBean" class="com.zxl.spring.RefMessageBean" >
	    <constructor-arg value="hello!!" />
	</bean>	 -->
	<!-- [][][] -->
	
	<!-- constructor -->
	 <!-- <bean id="messageBean" class="com.zxl.spring.MessageBean" autowire="constructor" />
	<bean class="com.zxl.spring.RefMessageBean">
	    <constructor-arg value="hello!!" />
	</bean>  -->
	<!-- [][][] -->
	
	<!-- byName -->
	<!-- <bean id="messageBean" class="com.zxl.spring.MessageBean" autowire="byName" />
	<bean id="refMessageBean" class="com.zxl.spring.RefMessageBean" >
	    <constructor-arg value="hello!!" />
	</bean>  -->
	<!-- [][][] -->
	
	<!-- byType -->
	<bean id="messageBean" class="com.zxl.spring.MessageBean" autowire="byType" />
	<bean id="refMessageBean" class="com.zxl.spring.RefMessageBean" >
	    <constructor-arg value="hello!!" />
	</bean> 
	<!-- [][][] -->
</beans>




你可能感兴趣的:(Java Spring Tutorial -- autowire byName, byType, constructor)