spring ioc---xml配置bean时,继承配置数据

版权声明:仅供学习交流使用 https://blog.csdn.net/drxRose/article/details/84948834

官方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();
	}
}

猜你喜欢

转载自blog.csdn.net/drxRose/article/details/84948834