03 spring bean in the template, Inheritance and Overrides

In this section we continue to look at the spring in the bean-related features: templates, inheritance and coverage.

1, the premise of restraint

2, Procedure

  • Net.wanho.entity.User.java created in the src folder, as follows:
public class User{
  private int id;
  private Strig name;
  //提供get/set方法,提供无参有参方法
}
  • Creation bean-template.xml in the src folder, as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="user" class="net.wanho.entity.User">
        <property name="id" value="123"></property>
        <property name="name" value="ali"></property>
    </bean>
    <!--继承上面的user,并且重写name-->
    <bean id="user1" parent="user" p:name="zhangli"></bean>
    <!--这就是一个模板-->
    <bean id="abstractuser" abstract="true" p:name="ali" ></bean>
    <!--实现上面的模板-->
    <bean id="user2" class="net.wanho.entity.User" parent="abstractuser"></bean>
</beans>
  • In the src folder, create Test.java test class, as follows:
public class Test{
      public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean-template.xml");
        User user= applicationContext.getBean("user",User.class);
        User user1= applicationContext.getBean("user1",User.class);
        User user2= applicationContext.getBean("user2",User.class);
    }
}

The above is the use of spring in the bean template, inheritance and coverage.

Guess you like

Origin www.cnblogs.com/alichengxuyuan/p/12554732.html