JavaBean的定義可序列化
提供無參構造
提供getter/setter方法
疑問
在學習 Spring 的過程中發現很多 bean 對象并沒有實現 Serializable 接口或提供其他可序列化的操作。這種也叫 bean?或者 bean 也可以不提供序列化操作?
解決
stackoverflow 一番后,發現跟我有同樣疑惑的人還不少。
最終答案
用戶 keya 的回答如下:JavaBeans:
At a basic level, JavaBeans are simply Java classes which adhere to certain coding conventions. Specifically, classes thathave public default (no argument) constructors
allow access to their properties using accessor (getter and setter) methods
implement java.io.Serializable
Spring Beans:
A Spring bean is basically an object managed by Spring. More specifically, it is an object that is instantiated, configured and otherwise managed by a Spring Framework container. Spring beans are defined in Spring configuration files (or, more recently, with annotations), instantiated by Spring containers, and then injected into applications.
大致翻譯JavaBeans:
簡單來說,JavaBeans 只是遵循了特定編碼規范的 Java 類,即提供默認公有無參構造
提供 getter/setter 方法
實現java.io.Serializable接口
Spring Beans:
Spring bean 是由 Spring 管理的對象。具體來說,它是由 Spring Framework 容器實例化、配置和管理的對象。Spring beans 在 Spring 配置文件中定義(近來更多使用的是注解的方式實現),由 Spring 容器實例化,然后注入到應用程序中(博主理解,即DI)。
補充
答主 keya 還提到Note that Spring beans need not always be JavaBeans. Spring beans might not implement the java.io.Serializable interface, can have arguments in their constructors, etc.
This is the very basic difference between JavaBeans and Spring beans.
For more information, refer to the source of the above text, Shaun Abram’s article JavaBeans vs Spring beans vs POJOs.
大意:Spring beans 不一定是 JavaBeans。Spring beans 可以不實現java.io.Serializable接口,也可以提供有參構造等等。
Shaun Abram 的文章中主要有兩點補充:Spring beans 可以是 POJOs 嗎?可以是,并且通常是。也可以不是,比如Spring也可以用于EJB(簡單理解就是一種重量級Java對象)。
Spring beans 可以是 JavaBeans 嗎? 答案同樣,可以是,并且通常是。也可以不是。
最后,根據本人實測,Spring bean可以不實現java.io.Serializable接口
可以不提供構造方法
可以不提供getter/setter方法
即,Spring bean 和 JavaBean 沒有半毛錢關系。