Java Bean 与 Java Class 的区别

文章目录

    Java 中的名号总是很唬人。Java Bean 初看,完全不知所谓。

    Bean - 豆子的意思。

    Java Bean 实际是就是一个普通的 Java Class,但是需要满足三个要求

    • 所有属性为 private,只允许通过 setXXX, getXXX 进行操作
    • 一个不需要初始化参数的 constructor
    • 实现了 Serializable

    当然,到这里,依然不知道 Java Bean 有什么蛋用!

    Java Bean 存在的意义是什么?这样设计有什么考虑?

    但是当与 The IoC container 结合着来看,就能明白 Java Bean 的优势了

    例如

    services.xml 中的配置

      <bean id="petStore"
            class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
        <property name="accountDao" ref="accountDao"/>
        <property name="itemDao" ref="itemDao"/>
        <!-- additional collaborators and configuration for this bean go here -->
      </bean>
    

    daos.xml 中的配置

      <bean id="accountDao"
          class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapAccountDao">
        <!-- additional collaborators and configuration for this bean go here -->
      </bean>
    
      <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapItemDao">
        <!-- additional collaborators and configuration for this bean go here -->
      </bean>
    

    从 services.xml 中 petStore 的两个属性均采用依赖注入的方式来配置,就明白了,这样做优势很明显。

    • 不在 Java Bean 中使用其他 Class 的实例,这样做是为了复用。通过依赖配置,很好的做到这一点。
    • 一个 Class 内部如果需要示例化其他 Class, 那么这是无法复用的。

    参考

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式