您好,登录后才能下订单哦!
密码登录
            
            
            
            
        登录注册
            
            
            
        点击 登录注册 即表示同意《亿速云用户服务条款》
        这篇文章将为大家详细讲解有关如何在Spring中定义抽象Bean和子Bean,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
一 配置
<?xml version="1.0" encoding="GBK"?> <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-4.0.xsd"> <!-- 定义Axe实例 --> <bean id="steelAxe" class="org.crazyit.app.service.impl.SteelAxe"/> <!-- 指定abstract="true"定义抽象Bean --> <bean id="personTemplate" abstract="true"> <property name="name" value="crazyit"/> <property name="axe" ref="steelAxe"/> </bean> <!-- 通过指定parent属性指定下面Bean配置可从父Bean继承得到配置信息 --> <bean id="chinese" class="org.crazyit.app.service.impl.Chinese" parent="personTemplate"/> <bean id="american" class="org.crazyit.app.service.impl.American" parent="personTemplate"/> </beans>
二 接口
Axe
package org.crazyit.app.service;
public interface Axe
{
   public String chop();
}Person
package org.crazyit.app.service;
public interface Person
{
   public void useAxe();
}三 实现类
1 American
package org.crazyit.app.service.impl;
import org.crazyit.app.service.*;
public class American implements Person
{
   private Axe axe;
   private String name;
   public void setAxe(Axe axe)
   {
      System.out.println("Spring执行依赖关系注入...");
      this.axe = axe;
   }
   public void setName(String name)
   {
      this.name = name;
   }
   public void useAxe()
   {
      System.out.println("我是美国人:名字为:" + name
        + "。正在用斧头" + axe.chop());
   }
}2 Chinese
package org.crazyit.app.service.impl;
import org.crazyit.app.service.*;
public class Chinese implements Person
{
   private Axe axe;
   private String name;
   public void setAxe(Axe axe)
   {
      System.out.println("Spring执行依赖关系注入...");
      this.axe = axe;
   }
   public void setName(String name)
   {
      this.name = name;
   }
   public void useAxe()
   {
      System.out.println("我是中国人:名字为:" + name
        + "。正在用斧头" + axe.chop());
   }
}3 SteelAxe
package org.crazyit.app.service.impl;
import org.crazyit.app.service.*;
public class SteelAxe implements Axe
{
   public String chop()
   {
      return "钢斧砍柴真快";
   }
}4 StoneAxe
package org.crazyit.app.service.impl;
import org.crazyit.app.service.*;
public class StoneAxe implements Axe
{
   public String chop()
   {
      return "石斧砍柴好慢";
   }
}四 测试类
package lee;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.*;
import org.crazyit.app.service.*;
public class BeanTest
{
  public static void main(String[] args)
  {
    ApplicationContext ctx = new
      ClassPathXmlApplicationContext("beans.xml");
  }
}关于如何在Spring中定义抽象Bean和子Bean就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。