1. 程式人生 > >spring ioc---xml配置bean時,繼承配置資料

spring ioc---xml配置bean時,繼承配置資料

官方xsd文件中,對bean標籤的屬性parent的說明:

The name of the parent bean definition. Will use the bean class of the parent if none is specified, but can also override it. In the latter case, the child bean class must be compatible with the parent, i.e. accept the parent's property values and constructor argument values, if any. A child bean definition will inherit constructor argument values, property values and method overrides from the parent, with the option to add new values. If init method, destroy method, factory bean and/or factory method are specified, they will override the corresponding parent settings. The remaining settings will always be taken from the child definition: depends on, autowire mode, scope, lazy init.

對bean標籤的屬性abstract的說明:

Is this bean "abstract", that is, not meant to be instantiated itself but rather just serving as parent for concrete child bean definitions? The default is "false". Specify "true" to tell the bean factory to not try to instantiate that particular bean in any case. Note: This attribute will not be inherited by child bean definitions. Hence, it needs to be specified per abstract bean definition.​​​​​​​

總之,

  • 使用parent屬性的時候,繼承本身支援的配置資料,簡化xml配置檔案.
  • 使用abstract,除標記為抽象類,讓容器不對其初始化,也可結合parent屬性,將abstract宣告的bean作為一個通用配置資料模板.

類物件

package siye;
public class People
{
	String name;
	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;
	}
}
package siye;
public class User
{
	String name;
	int age;
	int sex;
	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;
	}
	public int getSex()
	{
		return sex;
	}
	public void setSex(int sex)
	{
		this.sex = sex;
	}
	@Override
	public String toString()
	{
		return "User [name=" + name + ", age=" + age + ", sex=" + sex + "]";
	}
}

配置檔案,config.xml

<bean id="people" class="siye.People">            
	<property name="name" value="username" />     
	<property name="age" value="22" />            
</bean>                                           
                                                  
<bean id="user" parent="people" class="siye.User">
	<property name="sex" value="0" />             
</bean>                                           

測試類

package siye;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UnitTest
{
	public static void main(String[] args)
	{
		String path = "classpath:/siye/config.xml";
		ClassPathXmlApplicationContext context =
				new ClassPathXmlApplicationContext(path);
		User user = (User) context.getBean("user");
		System.out.println(user);
		context.close();
	}
}