Simply put, what does getBean do in Spring?

Consider a line of code like this

AutomobileDriver ad=(AutomobileDriver)appContext.getBean("increaseSpeed"); 

Suppose there is an IncreaseSpeed class that inherits from the AutomobileDriver class

What does getBean do? What is the main function of this?

+7
source share
4 answers

In "simple unprofessional terms":

  • It is understood that Spring was asked to create an instance of an object (possibly in an XML configuration file) that is identified (through Spring) as having the identifier "increase Speed" and has a class or parent class AutomobileDriver .

  • You request a Spring context to reference (a) the default, a previously created object (this is called a singleton), or (b) a new instance of that object (prototype).

+4
source

In Spring, you can define a bean and give it an identifier. Spring usually prefers you use dependency injection to access the bean. However, Spring provides getBean as another way to access a bean by its identifier.

Basically, your code will return a bean instance with the identifier "speed increase".

+2
source

This code requests a bean named increaseSpeed from the Spring application context. Think of the application context as a pool of accessible objects that has been configured from your Spring configuration XML configuration. When the application context starts, it creates beans in the configuration. This call simply requests one that already exists. The application context returns this "bean" as java.lang.Object , so you must apply it to the appropriate type.

You can see this call as an entry point in a Spring application. This call is necessary to get the first object out of the application context - from there this object can have references to other objects that were introduced using Spring.

+2
source

A bean is a component that provides some functions, the name bean means that it will increase speed.

These components are registered in a context called the "application context", and can be viewed by name. Therefore, if you want to increase speed, look at your application context for something that could do this.

More technically:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/

+1
source

All Articles