A Java object can be a JavaBean, a POJO and a Spring bean all at the same time.
POJO is an acronym for Plain Old Java Object. The term was coined by Martin Fowler et. al., as a ‘fancy’ way to describe ordinary Java Objects that do not require a framework to use, nor need to be run in a application server environment. It is often used to distinguish simpler, lightweight Java objects from ‘heavyweight’ code like EJBs. The use of these kind of lightweight objects in programming is described in books such as “POJOs in Action” and advocated by frameworks like Spring.
The concept of JavaBeans was originally devised for Swing to facilitate the development of standalone GUI components, but the pattern has been repurposed for the land of Spring beans and back-end persistence with Hibernate.
JavaBeans are classes that encapsulate many objectss into a single object (the bean). The name “Bean” was given to encompass the following standards, which aims to create reusable software components for Java.
- Must implement Serializable.
- It should have a public no-arg constructor.
- All properties in java bean must be private with public getters and setter methods.
- The class should be serializable.
- Have a public default constructor.
- class properties are private, accessed by getter and seter.
- properties, events, and methods can be reused in other applications
- register events
- can be saved to persistent storage and restored
- public no-arg constructor cannot guatantee a proper initialization
- Java Beans are mutable in nature.
- Boilerplate code, like getter and setter.
Java Bean VS POJO
An object in Java may be a POJO but not a JavaBean. For instance, it may implement an interface or extend specified classes, but because it refers to objects that are stateful and/or exist outside the scope of the Java Virtual Machine (JVM)—for example, HTTP or database connections —it cannot reasonably be serialized to disk and then restored.
Spring beans are just object instances that are managed by the Spring IOC container. They’re created based on
BeanDefinition describe the properties of a bean.
It contains the following meta data:
- A package-qualified class name
- Bean behavioral configuration: scope, lifecycle callbacks, and so forth
- collaborators or dependencies
- Other configuration settings
- constructor arguments
- autowiring mode
- lazy-initialization mode
- initialization method
- destruction method
three ways of defining a Spring bean
- Using stereotype
@Beanannotation in a custom Java configuration class
Java Bean VS Spring Bean
- Spring bean is managed by Spring IOC, Java Bean is not.
- Java Bean is always serializeable, Spring Bean doesn’t need to.
- Java Bean must have a default no-arg constructor, Spring Bean doesn’t need to.
- A Java object can be a JavaBean, a POJO and a Spring bean all at the same time.