How is Spring Container created? - java

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

Related

Why you have to anotate classes in Spring boot with service etc.?

Everyone says that it's because spring boot in that case will know that service exists. But if you call that service's method in another method that you try to run when the web app is running. Should it know the service exists without the annotation or not?
The main reason you put these stereotype annotations to classes is creating beans in application context and let the IOC container to provide the management and configuration of these beans depending on their stereotypes.
Spring is an IOC container responsible for instantiating, configuring and assembling these beans. And putting stereotype annotation is just a way to define bean.
You can define beans in various ways such as using #Bean annotation, stereotype annotations, XML definitions etc. and if you don't define your bean, the IOC container can not detect and instantiate the service.

Use of Bean configuration XML File

I am a new user of Spring framework. I am facing some confusion in understanding the difference between core spring framework and spring boot. As far as I understand, Spring boot is a framework which performs the initial setup automatically (like Setting up Maven dependencies and downloading the jar files) and comes with an embedded Tomcat server which makes it ready to deploy in just one click., Whereas, Spring MVC requires manual setup. All the tutorials that I watched for core spring show bean configuration using bean factory which configures the beans using a .XML file. In Spring boot, this bean configuration file is absent. My question is, what is the use of this bean configuration file? I did not find any legitimate use of this file in making a REST service with spring. I didn't see any use of the Application Context, Bean Factory in creating web application. Can someone point out how can bean factory be used in Spring web apps? Is there any fundamental difference between core spring and spring boot other than the additional components?
The Spring application context is essentially the "pool" of beans (service objects, which include controllers, converters, data-access objects, and so on) and related information that define an application; I recommend the reference introduction. In theory, you can get complicated with the context setup and have hierarchical organization and such, but in most real-world cases you just have a single plain context.
Inside this context you need to install all of the beans that provide the logic for your application. There are several possible ways to do this, but the two main ways are by providing XML files with have directives like bean (define an individual bean) or component-scan (automatically search for classes with certain annotations, including #Controller) and by using Java classes annotated with #Configuration, which can use annotations and #Bean methods.
The XML style is generally older, and newer applications mostly use Java configuration, but both provide entries that are collected into the context, and you can use both simultaneously. However, in any application, you have to provide some way of getting the registration started, and you will typically have one "root" XML file or configuration class that then imports other XML files and/or configuration classes. In a legacy web.xml-based application, you specify this in your servlet configuration file.
Spring Boot is, as you said, essentially a collection of ready-to-go configuration classes along with a mechanism for automatically detecting configurations and activating them. Even this requires a configuration root, though! This is the #EnableAutoConfiguration instruction, frequently used through its composite #SpringBootApplication. The application context and configuration mechanisms work normally once Boot finds them and pulls them in. Spring knows where to get started because you give it an explicit instruction to build a context starting with that entry point, usually with SpringApplication.run(MyApplication.class, args).
The embedded-server configuration just happens to be a particular set of configuration that is really useful and comes with one of the Boot starter packages. There's nothing there that you couldn't do in a non-Boot application.

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).

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.

Difference between JavaBean and Spring bean

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.

Categories