61

Java中的bean

 4 years ago
source link: https://niyanchun.com/bean-in-java.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java中经常听到和用到Bean,你能说清楚Bean这个概念吗?如果不能,本文可以帮你解惑。不是特别准确的划分的话,Java中有两类Bean:JavaBean和Spring中的Bean。

JavaBean

JavaBean比较好理解,因为它是有标准的(可以点击 这里 从oracle官方下载specification),有兴趣的可以阅读一下,内容还挺多的。简单来说,这个标准规定了符合以下四个条件的Java类就称之为JavaBean:

  • 必须 实现了 SerializableExternalizable ,即JavaBean必须是可序列化的;
  • 必须 包含一个public的无参构造函数;
  • 所有类的属性 必须 要有对应的public的get和set方法;
  • 所有类属性 应该 是私有的。

这就是JavaBean的规范要求,其实比较简单,就是一个概念定义。这里还要提一下的就是Java中的POJO(Plain and Old Java Object),这个概念没有什么标准,属于约定俗成的概念,比较简单的Java类就可以称之为POJO,至于简单的界限是什么,没有明确的标准。一般JavaBean都属于POJO,但POJO未必是JavaBean。

Spring Bean

在Spring中,不夸张的说,一切都可以是Bean(当然还是有点夸张了)。但用过Spring的人都知道,如果按照JavaBean的规范看的话,Spring中的Bean大多不算是JavaBean,至少很少有人会实现序列化。所以,在Spring中,Bean这个概念被扩大化了,Spring中的Bean更像是POJO。官方的解释如下:

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. Beans, and the dependencies among them, are reflected in the configuration metadata used by a container.

简单说: 在Spring中,被Spring容器管理的那些类(对象)都是(Spring)Bean


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK