I am new in j2ee and want to know about java beans. I have one java class, and use an instance of that class in another class. What are the reasons I should define the first class as a java bean and then inject an instance of that in another class? what are the advantages of that? What kind of classes are better to be defined as java beans? For example, I may have a pojo to be used in ORMapping, a class to make UI (I use vaadin to make UI) , another class to do business logic (for example, calculate the result specific mathematical formula) , and another class to do DB operations. Which one is the candidate to be defined as a java bean, using ejb or spring?
3 Answers
The JavaBeans designation only concerns the convention of providing accessor methods for the public properties of the class. POJO is an orthogonal concept and a Java bean may easily also be a POJO.
You seem to be contemplating beans in the context of the Spring IoC container. Spring uses the term "bean" in quite a loose sense and the actual objects may not even comply with the JavaBeans specification. Most typically they provide only a setter (no getter).
Now, the advantages of letting an IoC container wire together interdependent objects are many and this practice is warmly recommended. Some points:
- the concern of bean instantiation is centralized;
- less coupling between beans: the client bean doesn't need to know how to initialize its collaborators;
- trivially easy handling of the otherwise massive problem of circular dependencies;
- no boilerplate code involving instantiation sprinkled around code;
- easy reuse of singletons => saves memory, brings order and consistency to the object system;
- declarative control of bean lifecycle, again with no boilerplate code in the beans themselves.

- 195,646
- 29
- 319
- 436
From the javadocs:
JavaBeans™ makes it easy to reuse software components. Developers can use software components written by others without having to understand their inner workings.
To understand why software components are useful, think of a worker assembling a car. Instead of building a radio from scratch, for example, she simply obtains a radio and hooks it up with the rest of the car.

- 67,789
- 12
- 98
- 136
Java beans is used to store data persistently in database. this class consist of setter and getter method. you need to create another java class to do this operation

- 107
- 1
- 2
- 7