Difference between JavaBean and Spring bean - java

I am new to Spring MVC and have a little idea of the usage of java beans in Java.
What is the basic difference between a Java bean and Spring bean?

JavaBeans:
At a basic level, JavaBeans are simply Java classes which adhere to certain coding conventions. Specifically, classes that
have 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.
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.

Java bean is a class that should follow following conventions:
1.Must implement Serializable.
2.It should have a public no-arg constructor.
3.All properties in java bean must be private with public getters and setter methods.
Spring beans are the objects that form the backbone of your application and are managed by the Spring IoC container .

Spring Bean:
A class which is developed as part of a spring application. Its life cycle which is managed by Spring Container is called as Spring Bean.

Java beans and Spring beans are more related than different.
For a Java class to be usable as a Java bean, its setter- and getter-method names need to be as per the JavaBean guidelines (also called design patterns) for properties. If such a Java class is instantiable & manageable by the Spring IoC container, it is a Spring bean. To achieve this, the programmer wires the class as a bean definition of a suitable scope by using XML config files or annotations or a mix of both. The programmer can create new Spring beans out of existing Spring beans by wiring further by passing the latter to constructor-arguments of the former either as string-names as <idref> elements or by dependency injection (it can be recursive).
This answer may be read in conjunction with my this SO answer to get more background information.

Related

How to understand Bean in Spring?

I am a beginner of Spring and I still can't understand clearly what Bean is. From its definition, it seems a object that is determined by some pre-set configuration files or using annotation on a class. Once the spring starts up, the bean has been created. But can Spring use DI to create some instances of which attributes are not pre-determined?(Like, a user posts a json from website to Spring. And this json contains some data that are used to new a instance. Can Spring use this json to create the instance by using DI?)
Bean is just the object created by your spring application. As you know any spring application has several interacting objects working together to give rise to the desired programmed behavior.
A Bean is basically a managed object i.e at run time the IOC container creates the bean object based on its definition supplied by the coder or as configured in the apllicationContext.xml file under beans tag, and injects it to other classes as required.
Any Spring application is basically a conglomeration of various objects interacting with each other, these objects or beans collaborate to create the application.
A Bean's lifecycle is managed by the Spring IOC container.
The JSON consumed by the Spring Application is taken care of by the HttpMessageConverter. When recieving a new request, the Spring framework will use the content-type header to determine the media type of the request.
It will then try to find the corresponding converter, available in the classpath of the application, to convert the Request body.
Thus its clear that the incoming request body object is not managed by the Spring IOC container and hence is not a Bean.
But these deserialized instances are used as Data Transfer Objects in a Spring application's various layers like, service, DAO, controller.
Spring beans are the objects that comprise your application and are managed by the Spring framework. Comparing them to the concepts of JavaBeans and POJOs provides some explanatory context, and the Spring reference documentation contains extensive documentation of Spring beans, including this summary:
A bean definition essentially is a recipe for creating one or more
objects. The container looks at the recipe for a named bean when
asked, and uses the configuration metadata encapsulated by that bean
definition to create (or acquire) an actual object.
Also included in the reference documentation are descriptions of various ways to instantiate beans via an xml-based or annotation-based configuration approach as well as the Java Config approach (which also uses annotations). This is managed by the Spring BeanFactory interface (API here; source here).
The #Bean annotation is used to indicate that a method instantiates,
configures and initializes a new object to be managed by the Spring
IoC container. For those familiar with Spring’s XML
configuration the #Bean annotation plays the same role as the
element. You can use #Bean annotated methods with any Spring
#Component, however, they are most often used with #Configuration
beans.
You refer in the question to Dependency Injection (DI), a design pattern based on the Inversion of Control principle, which is a critical part of the Spring Framework, particularly for bean instantiation. DI allows values to be passed into the object from outside. The Spring documentation describes both the constructor-based and setter-based approaches to DI provided by the Spring IoC container for instantiating objects (beans).

Can I inject properties to third-party beans?

Suppose I have classes, which were instantiated not by Spring. For example, they can be instantiated by deserializer or by JavaFX.
Can I code these classes in the same way I code Spring beans and inject properties into them later?
Actually, I would like a routine, which would scan class with reflection, find all #Autowired annotations in it and inject values from application context?
Will this happen, if I call applicationContext.getBeanFactory().registerSingleton("myName", myBean)? Note, that I would no limit myself with singletons.
If beans are not instantiated by Spring, then you cannot ask Spring to inject dependencies or advise them.
This is a common mistake I see Spring neophytes make. They call new to instantiate a bean with annotations and can't understand why their dependencies aren't injected.
Spring will handle all the beans you instantiate with the bean factory. You are on your own with all others created using new.

spring vs ejb3 - what is different in beans injection?

is it correct that in spring I can inject my own beans , and in ejb3 I can inject only ejb3 beans ? if so how can ejb3 be a replacement to Spring?
Besides the fact that you can use CDI for injecting different types of beans, what do you mean by "ejb3" beans and how those beans are not yours as in case of spring? Spring injects any kind of bean and you do that either by declaring it in XML (old approach) or by specifying an annotation (#Component, #Service, etc.). Which is the case also for EJB3 (you can use #Stateless instead of #Service, just to make an analogy).
So, in JEE environment one can be replaced with the other (from this point of view, Spring has some advantages as it sets the grounds for fast development, providing additional helpers, libraries, frameworks on top of JEE specification - see Spring Data JPA for one).
So, I think is a matter of how you design your application to use one or the other.
In a Java EE environment, you can not only use EJB, but also CDI.
see How do CDI and EJB compare? interact?

How is Spring Container created?

I am studying for the Spring Core certification and I have following doubt about this question:
What is meant by “container” and how do you create one?
I know that the Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction. The Spring container uses dependency injection (DI) to manage the components that make up an application. These objects are called Spring Beans which we will discuss in next chapter.
And I know that there exist 2 containers:
Spring BeanFactory Container: This is the simplest container providing basic support for DI and defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purposes of backward compatibility with the large number of third-party frameworks that integrate with Spring.
Spring ApplicationContext Container: This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.
Ok...this is pretty clear for me but what is the correct answer about How to create a container?
I think that it is automatically created by the Spring when it reads the configuration class or the XML configuration file.
Or not? What am I missing?
In short, "The Container" is a Spring instance in charge of managing the lifecycle of your beans.
To create one, basically, you should do something like
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context.xml");
Remember replacing /application-context.xml by the file where you define your own Spring beans.
Take a look at http://www.springbyexample.org/examples/intro-to-ioc-creating-a-spring-application.html
You could also substitute the xml by a configuration class. On that case you should have something like this:
#Configuration
public class Myconfig{
#Bean
public MyBean myBean(){
return new MyBean();
}
}
For this, take a look at http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

Where do those beans returned by Spring getBean method come from?

Could you please list all possible sources of getBean?
BTW, If I just write context.getBean(SomeInterface.class), can I get the implementation of the interface class?
They come from the Spring application context (which is what you are calling the getBean method on).
Spring has this concept of an application context, which is an object that contains things such as all the beans managed by Spring.
You put beans in the application context by configuring them in a Spring XML configuration file or by annotating classes with annotations such as #Component, #Service etc. and then letting Spring find them by scanning packages for those classes.
If you write context.getBean(SomeInterface.class) and there is a Spring bean that implements that interface, then that method call will return the bean that implements the interface.
These are basic concepts of the Spring framework. See chapter 5, The IoC Container in the Spring documentation for a detailed explanation of how it works.
If you go into the ApplicationContext class hierarchy, you will find that all spring Application Context file are child of org.springframework.core.io.DefaultResourceLoader class.
What DefaultResourceLoader does is it get the current thread context class loader(if none is provided). So we can understand that all application context file first load the classes defined. Application Context load all the beans defined in xml file, marked using #Bean annotation or other available spring annotations. Once the context scan through the annotation and/ or xml and load all the beans in the class loader. Context first create the dependencies and inject them in dependent.
To get context.getBean(SomeInterface.class), please refer below documentation.
http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/context/support/AbstractApplicationContext.html#getBean(java.lang.Class)
As per my understanding of documentation, you shall get the bean if exact one implementation bean class is defined.

Categories