Spring Beans

1. What are Spring Beans?

Spring Bean is an object that is managed by the Spring Framework. A Spring Bean is
instantiated, configured, and managed by the Spring Framework container (IoC
container). You can define the beans in a configuration file or use annotations. The
beans are then instantiated by the Spring IoC container, added to the Spring
ApplicationContext, and injected into your application at the points they are asked for.

2. What are the different Bean scopes?

Beans, which are Spring-managed Java classes are created and wired by the Spring
Framework. Spring allows you to define how these beans will be created. The scope
of the bean is one of those definitions. To specify the bean scope, you can either use
Spring annotations or define it in the configuration file.
Spring Framework supports the following scopes:

  • Singleton: If you use this bean scope, no matter how many times you call the getBean() method, the same bean instance will be returned. This is the default bean scope in Spring.


  • Prototype: If you use this bean scope, every getBean() call creates a new instance of Spring bean.
  • Request: If you use this bean scope, it allows each HTTP request to have its own instance of the bean created and supplied by Spring Framework. This bean scope is available on web-aware application context.
  • Session: If you use this bean scope, it allows the Web application to have bean instance per session basis. 
  • Global-session: If you use this bean scope, it allows bean instance per globalsession. This bean scope is available on Web-aware application context.


3.What is the default scope of Bean in SpringFramework?


The default scope of a Spring Bean is Singleton.


4. Are Singleton Beans thread safe?

No, Singleton Beans are not thread safe. Singleton Spring Bean has no relation with
thread safety. Spring container only manages life-cycle of objects. So, if a non-thread
safe object is injected then obviously it is not thread-safe. To make it thread-safe you
have to handle it programmatically.
If it is a Web-application, request scope can achieve thread-safety as for each new
request it creates a new object. Similarly, prototype scope will also do this as for each
invocation it creates a new bean.

5. What are inner beans in Spring?

Inner beans are those beans which are implicitly made anonymous but also scoped as
a prototype. If you want Beans to be accessed by any other bean used in your
application, you need to define them as inner beans. An inner bean definition does not
require a defined id or name; the Spring container ignores these values. The container
also ignores the scope of the bean.
19. What is bean autowiring?
The process of injecting the dependencies of a Spring bean during initialization of the
bean is called bean wiring. It is basically a process that associates the beans together
in the container. When wiring beans, you should tell the container what beans are
needed and how the container should use dependency injection to tie them together.
Using bean autowiring, you need not define the bean configuration. That is, you need
not define the dependency of each bean. To do so, you can just use
the autowire attribute of the bean and specify which dependency type it must be, such
as byName or byType.
An example of auto-wiring with the byName type is this.
@Bean(autowire=Autowire.BY_NAME)
The preceding annotation is the equivalent of this XML configuration.

6. What are the different autowiring modes?

The different autowiring modes are:

  • no: This is the default mode. It specifies no autowiring. Hence you need to set it manually via the ref attribute.
  • byname: It specifies auto-wiring by property name. If the name of a bean is same as the name of other bean property, Spring will auto-wire it. 
  • byType: It specifies auto-wiring by property data type. If the data type of a bean is compatible with the data type of another bean property, Spring will auto wire it.
  • constructor: It specifies the autowiring byType mode in constructor argument.

7. What are some limitations of autowiring?

Some limitations of autowiring are:




Simple properties such as primitives and Strings and arrays of such simple
properties cannot be autowired. This is a limitation by design.
The information of autowiring will not be available to the tools that generate
documentation from the Spring container.
Autowiring is less precise than explicit wiring. In autowiring, the relationships
between your Spring-managed objects are no longer documented explicitly.
Autowiring is based on the idea that you indicate what properties are to be
autowired and Spring deduces its corresponding value. This means, in autowiring,
you run the risk of providing more than one match.On the other hand, explicit
wiring, as its name implies, requires the target bean to be mapped with an explicit
property name/value pair for Spring to use to link the two objects.
Ambiguity arises when there are dependencies that expect a single value, but
multiple beans exist. For example, there are multiple beans within the container
that match the type specified in the setter methods or constructor arguments to be
autowired. In such situations, when no unique bean definition is present, the
container throws an exception of type NoSuchBeanDefinitionException.

8. What are Lazy-initialized beans?

Spring’s bean factory, when first created, pre-initiates the Spring beans of the
application. This is a good practice as it resolves any dependency error at the time of
start-up. However, this might not be applicable for all types of applications as bean
instantiation is both resource and time-consuming.
If an application contains a large number of beans, instantiating those at start-up takes
considerable time. Also, a significant amount of memory is required for storing all the
bean instances. A solution is to instantiate a bean only when required. In Spring such
beans are called lazy-initialized bean. A bean that is lazily initialized asks the IoC
container to create its instance when it is first requested for and not at start-up.
The @Lazy annotation marks a bean as lazy-initialized.


9. Explain Spring bean lifecycle and callbacks in
brief

When a bean is instantiated, it might be required to perform some initialization to get

it into a usable state. Similarly, when the bean is not required it must be removed from
the container and some clean-up process performed. All these happen during the
lifecycle of a Spring bean.The sequence of a bean lifecycle in Spring is this:
Instantiation: First the spring container finds the bean’s definition from the
configuration file or annotation, and instantiates the bean.
 Property population: Using dependency injection, Spring populates all
properties as specified in the bean definition.
 Setting Bean name: The bean name is set by passing the bean’s id
to setBeanName() method when the bean implements BeanNameAware interface.
In annotation based beans, the value field indicates the bean name.
 Pre Initialization: If there are any objects of BeanPostProcessors that are
associated with the BeanFactory, then the
method postProcessBeforeInitialization() will be called even before the properties
for the Bean are set.
 Bean initialization: If the Bean class implements the InitializingBean interface,
then the methodafterPropertiesSet() will be called once all the Bean properties
defined in the configuration file are set. If the configuration file contains an init-
method attribute in the Bean definition, then the value for the attribute will be
resolved to a method name in the Bean class and that method will be called.
 Post initialization: The postProcessAfterInitialization() method will be called if
there are anyBeanPostProcessors attached to the BeanFactory object.
 Ready to use: After all the above cycles, the beans defined are ready to be used
by the application.
 Destroy: If the bean implements a DisposableBean interface, it calls
the destroy() method to destroy the bean.
The Spring Framework provides several callback methods to create a bean and some
methods to destroy the bean in the Spring IoC container. Beans can be notified after
creation and before they are destroyed and removed from the bean container. This
involves specifying the callback method to be invoked by the container. Attribute init-
method="initMethodName" is specified for the initialization callback and destroy-
method="destroyMethodName" is specified for the destroy callback in the XML
configuration file. Here,initMethodName and destroyMethodName are names of
instance methods in the bean class.
The Spring Framework also provides marker interfaces that can change the behaviour
of your bean.InitializingBean and DisposableBean are two such marker Interfaces.
When a class implements these interfaces, the container calls afterPropertiesSet() for
the former and destroy() for the latter to allow the bean to perform certain actions
upon initialization and destruction.

10. What is component scanning and how it works?

In a traditional Spring application, the beans or components are declared in a
configuration file in order to allow the Spring container to detect and register them.
However, you should know that Spring is capable of auto scanning, detecting, and
further instantiating beans from the already defined project package. This can save
you from the tedious task of having to declare beans in a separate XML file.
Additionally, it helps in avoiding bean definitions.
As you know, Spring also supports annotation based configuration. You can annotate
the class with @Component, or one of the stereotype @Controller, @Service,
and @Repository to indicate that this class is a candidate component. A candidate
component is a component that matches against filter criteria and has a corresponding
bean definition registered with the containerAs @Repository, @Service, and @Controller are annotated with @Component. So,
you can just use @Component for all the components and Spring will auto-scan all of
them.

11. What is the NoSuchBeanDefinitionException
and how to fix it?

NoSuchBeanDefinitionException is an exception that the container throws
when BeanFactory cannot find a definition for a bean instance when asked for. This
may happen because of a non-existing bean, a non-unique bean, or a manually
registered singleton instance without an associated bean definition.
Trying to inject an undefined bean is a common cause of this exception. Often this
happens when the bean resides in a package that is not scanned by Spring.
Another reason for NoSuchBeanDefinitionException being thrown is because of a
non-unique bean. That is when two bean definitions exist in the context instead of one.
For example, consider two beans: BeanA and BeanB that implements
an IBean interface. If another Bean, sayBeanX auto wires IBean, Spring will throw an
exception of type NoSuchBeanDefinitionException. This happens because Spring
cannot figure out which implementation ( BeanA or BeanB) to inject. To fix this, use
the@Qualifier annotation to explicitly name the implementation to inject.

Comments

Popular posts from this blog

Spring Annotations

Spring Data Access

Spring Model View Controller (MVC)