javaspringspring-mvc

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


Solution

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