简体   繁体   中英

What is the advantage of java beans over POJOs in Java Spring?

I am quite new to the Spring framework, so I apologise for the stupid question. I have been learning about Java beans; I have also been reading about how the Spring Framework is a bean container and how there are different types of beans ( What is the advantage of using Java Beans? ).

However, I still don't get why they are so powerful. If we wanted to, say, create a Spring web app, couldn't we just do it without the use of beans, but just using POJOs? What are really the advantages of using Java beans over POJOs?

JavaBean can be or generally is a POJO even vice versa is true.
The only difference is Java bean follows certain conventions whereas POJO doesn't necessarily need to follow any conventions.

You can refer this link: Beans vs POJO .
From above link:

Spring managed objects are referred to as beans is because in the very early versions, Spring was intended only for use with JavaBeans. That is no longer the case of course: Spring can manage just about any object, even if it doesn't have JavaBean type characteristics such as default constructors or mutator methods (getters and setters). None the less, the term 'Spring beans' has stuck.

No there are no crucial advantages. To explain a bit,

There are 3 things that you have to clarify,

  1. JavaBeans

JavaBeans are simply Java classes which adhere to certain coding conventions

  1. POJO (Plain Old Java Object)
  2. Spring Beans

Spring beans are objects created and managed by the Spring framework.

None of the 3 terms discussed are mutually exclusive. A Java object can be a JavaBean, a POJO and a Spring bean all at the same time. All in all JavaBean is a special case of the POJO. There are no special powers to JavaBeans over POJOs inside the Spring container.

There are some contracts for JavaBean , like it should have public default constructor and getter setter, Serializable needs to be implemented.

But in case of POJO there is no such contracts. Its simpler than JavaBean

Writing your application using Spring beans can also make your application easier to test using mocking frameworks such as Mockito. You can use either mocks or stub implementations in your junit classes.

Without a managed bean container, a given class would need to instantiate all it's dependent objects - which makes it difficult to write unit tests for that class - it can be done, but it's harder.

With a dependency injection framework you can simply call the setters for your dependent object yourself in your unit tests using mock objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM