Sie sind auf Seite 1von 6

What are Beans in Spring framework?

The life cycle of beans consist of several call back methods


The Spring Beans are nothing but Java Objects that forms the that are broadly categorized into two groups.
backbone of a Spring application. Those beans are
instantiated, assembled, and managed by the Spring IoC  Post-initialization callback methods.
container. These beans are created using  Pre-destruction callback methods.
the configuration metadata definitionsupplied to the container,
for example, in the form of XML definitions.
Is a singleton bean thread safe in Spring Framework?
No. The singleton scoped beans are not thread-safe in Spring
All the beans in spring framework are singleton beans by framework.
default. An attribute in xml bean tag named "singleton" is set
to true then bean becomes singleton and if set to false then the
Explain the important life-cycle methods of a bean in Spring
bean becomes a prototype bean.
framework.
There are 2 important bean lifecycle methods.
What does a Spring Bean definition consists of?
A Spring Bean definition holds all the configuration metadata
The setup method called when the bean is loaded into the
required for the container to understand how to create a bean,
container.
manage its lifecycle and its dependencies.

The teardown method which is invoked when the bean is


Different Spring Bean Scope.
unloaded from the container.
1. singleton : Returns a single bean instance per Spring IOC
container.(default scope)
2. prototype : Returns a new bean instance each time when The bean XML tag has two important attributes init-
requested. method and destroy-method to define your custom
3. request : Returns a single bean instance per HTTP request. initialization and destroy methods. There are also the
4. session : Returns a single bean instance per HTTP session. equivalent annotations @PostConstruct and @PreDestroy.
5. global session : Return a single bean instance per global
HTTP session and only valid when used in portlet context. Explain inner beans in Spring framework?
Inner beans are spring beans that are used as a property of
How do I provide beans configuration metadata to the another spring bean.
Spring Container?
There are 3 ways to provide configuration metadata to the Spring's XML-based configuration metadata provides the use
Spring Container. of <bean/> element inside the <property/> or <constructor-
arg/> elements of a bean definition to declare inner beans.
 XML based configuration file. Inner beans are always anonymous and it is always scoped as
 Annotation-based configuration. prototypes.
 Java-based configuration.
What are the limitations of autowiring in Spring framework?
How do I define the scope of a bean in spring framework?
While defining a bean in Spring xml configuration, the scope  Overriding: You can still specify dependencies
also can be declared for the bean. The scope attribute of the using and settings which will always override
bean defines its scope. autowiring.
 Primitive data types: You cannot autowire simple
The scope attribute takes one of the five values: singleton, properties such as primitives.
prototype, request, session and global session.  Confusing nature: Autowiring is less exact than
explicit wiring, so if possible prefer using explicit
wiring.
Describe the lifecycle of a Bean in Spring framework.
The spring container loads the bean definition from the
XML file and instantiates the bean. Also it initializes the How do I inject java.util.Properties into a Spring Bean?
properties of the bean using Dependency Injection (DI) that <props> tag can be used to inject properties to a spring bean
are specified in the bean definition in XML file. as shown below.

Once spring container created the bean, Spring bean factory Explain @Required annotation in Spring framework.
will control and held responsible for managing the life cycle The @Required annotation applies to bean property setter
of beans. methods and it indicates that the represented bean property is
required and must be initialized in
XML configuration file at configuration time otherwise the
Once a bean is instantiated by the spring container, some of
container will throw
the initialization need to be performed to get it into a usable
a BeanInitializationException exception.
state. Similarly, when the bean is no longer required and about
to be removed from the container, some cleanup process may
be involved. public class Employee {
private Integer age; attribute. The @Resource annotation takes a 'name' attribute
private String name; which will be interpreted as the bean name to be injected.
public Integer getAge() {
return age; @Resource is specified by the JSR-250.
} @Required
How do I configure a bean in my spring application?
public void setAge(Integer age) { this.age = age;
Using bean xml tag, a spring bean can be configured. Bean tag
} has id attribute that specifies the bean name and
} the class attribute represents the fully qualified class name.
The RequiredAnnotation BeanPostProcessor bean post
processor checks if all the bean properties with the @Required What kind of exception does spring DAO classes throw?
annotation have been set. To enable this bean post processor, The spring DAO class do not throw any specific exceptions
you must register it in the Spring IoC container. such as SQLException instead it throws exceptions that
are subclasses of DataAccessException.
<bean
Explain the different ways to configure a Java class as
class="org.springframework.beans.factory.annotatio
Spring Bean.
n.RequiredAnnotationBeanPostProcessor" /> There are 3 different ways to configure a class as Spring Bean.
Explain @autowired annotation in spring framework.
XML Configuration is the most popular configuration. The
The @Autowired annotation provides fine-grained control
bean element tag is used in xml context file to configure a
over where and how autowiring should be accomplished. The
Spring Bean.
@Autowired annotation can be used to autowire a bean on the
setter method, constructor, a property or methods with
arbitrary names and/or multiple arguments. Using Java Based Configuration, you can configure a Spring
bean using @Bean annotation. This annotation is used with
@Configuration classes to configure a spring bean.
Autowired annotation on setter methods.

Annotation Based Configuration facilitates @Component,


The @Autowired annotation can be applied on setter methods
@Service, @Repository and @Controller annotations with
that eliminates the <property> element in
classes to configure them to be as spring bean. For these, we
XML configuration file. Spring performs byType autowiring
would need to provide base package location to scan for these
on the property setter method when marked as Autowired.
classes
Autowired annotation on bean properties.
Difference between id and name attribute of <bean> element
in a Spring configuration file.
Autowired annotation on properties eliminate the need of Per the Spring 3 documentation, 'you use the id and/or name
setter methods. When value for the autowired properties is set attributes to specify the bean identifier(s)'.
using <property> in the xml configuration, Spring
will automatically assign those properties with the passed
values or references. The name attribute behaves and functions similar
to id attribute on a bean but it allows the bean unique
identifier to contain special characters. Special characters
Autowired on Constructors. like #, @, $, *, / are not allowed in the id attribute.

A @Autowired constructor indicates that the constructor The name attribute allows for multiple 'aliases' that becomes a
should be autowired when creating the bean, even if no collection of identifiers that can be used to identify the bean
<constructor-arg> elements are used while configuring the whereas there can be only one id per container.
bean in XML file.

How do I make autowired bean property as optional? <bean id="myBeanID" name =


By default, the @Autowired annotation sets the dependency as "myBean1,myBean2,myBean2"
mandatory similar to @Required annotation, however, the
default behavior can be turned off by using required = class="net.javapedia.bean.EmpBean">
false option with @Autowired. Is Spring Bean with singleton scope thread safe?
The default scope of Spring bean is singleton, which means
What is @Resource annotation in Spring framework? that there be only one instance per context. Having a bean
javax.annotation.@Resource annotation can be applied on class level variable that any thread can update will lead to
fields or setter methodsfor dependency injection and inconsistent data. Hence in default mode spring beans are not
it follows by-name autowiring semantics, name extracted thread-safe.
from the name of the annotated setter/field or from the 'name'
Difference between @Resource and @Autowired in Spring The parent bean cannot be instantiated on its own because it is
framework. incomplete, and also it is explicitly marked as abstract.
@autowired wires by bean type whereas @resource wires by
name. What is spring bean pure inheritance template?
The spring bean definition with abstract attribute
Using @Qualifier along with the @Autowired functions as true with no class attribute are meant for only inheritance
exactly similar to the @Resource annotation. and sharing of properties that are termed as pure definition
template.
Explain lazy-init attribute of bean tag in Spring.
lazy-init attribute of <bean> tag is used to specify whether a Can a spring bean tag with no id or name attribute be created?
spring bean is to be lazily initialized or not. Yes. Some spring beans are not required to be accessed by any
other beans in the context file or by programmatically. So it
BeanFactory initializes all the spring beans lazily while does not require an id or name attribute as they are not
ApplicationContext initializes all singleton spring beans referenced.
eagerly. To make ApplicationContext to initialize the all the
spring bean lazily, lazy-init attribute need to be set to true. How do I inject value for a bean property of primitive type?
Can spring bean autowire on primitive types?
Following are the allowed values for lazy-init attribute.
No. @Autowired annotation expects a bean of the type to
present in the applicationContext.
true - lazy, IOC container creates the bean when it is first
requested.
How do I create a stateful bean in Spring framework?
Using the prototype bean scope, one can define a stateful
false - eager, IOC container creates the bean at startup. bean. Prototype scoped beans are instantiated every time it is
requested.
default - refers to the default-lazy-init attribute specified for
the <beans> Difference between request and prototype bean scope in
spring?
Can we fetch the inner bean from spring container using its id, Prototype scope creates a new instance
if an inner bean defines one? everytime getBean method is invoked on the
No. An inner bean cannot be accessed even if the id attribute ApplicationContext. Whereas for request scope, only one
is defined, getBean ("theInnerId") will fail instance is created for an HttpRequest.
with NoSuchBeanDefinitionException.
So in a HttpRequest, if the getBean method is called twice on
Explain Spring bean inheritance. Application and there will be only one bean instantiated and
Spring bean can exhibit inheritance behavior by defining reused, whereas the bean scoped to Prototype in that same
parent and child beans. The parent beans are configured using single HttpRequest would get 2 different instances.
the abstract attribute value being set to true. A child bean can
be configured using parent attribute on bean tag, parent bean What is the role of a Spring bean configuration file?
id as its value. The Spring bean configuration file defines all the beans that
will be initialized by Spring Context. When an instance of
A child bean definition inherits configuration data from a Spring ApplicationContext is created, it reads the spring bean
parent definition. The child definition can override few values xml file and initialize all of them. Once the context is
,add others as needed. initialized, it can be used to get different bean instances.

Spring Bean definition inheritance has nothing to do with Java Explain Circular Dependency scenario in Spring.
class inheritance but inheritance concept is similar. You can Consider a scenario where Class A requires an instance of
define a parent bean definition as a template and other child class B through constructor injection, and class B requires an
beans can inherit required configuration from the parent bean. instance of class A through constructor injection. If you
configure beans for the classes A and B to be injected into
What is Bean Definition Template in Spring framework? each other, the Spring IoC container detects this circular
Bean definition template also referred as parent beans can be reference at runtime and throws
used to define common bean definitions shared by other child a BeanCurrentlyInCreationException.
beans without redefining it.
The easiest solution to resolve the circular dependency issues
While defining a Bean Definition Template, class attribute would be editing the classes to have the dependency set by
may not be defined and should specify abstract attribute with setters rather than constructor.
its value as true.
public class A {
public A() { stateful beans: beans that can carry state (instance variables).
System.out.println("Creating instance of A"); These are created every time an object is required.
}
Can I define spring bean twice with same name in different
private B b; bean definition file?
Yes. When the second bean definition file loads, it overrides
public void setB(B b) { the definition from the first file. The main objective of this
System.out.println("Setting dependency B of A behavior is to ovrrride the previously loaded bean definition.
instance");
this.b = b; This behavior is configurable; DefaultListableBeanFactory
} allows to control this behavior using
setAllowBeanDefinitionOverriding().
}
public class B { Can I define spring bean twice with the same bean id in same
file?
public B() { No. It is not possible.
System.out.println("Creating instance of B");
} Explain JSR-250 annotation.
Spring supports JSR 250 annotations that
private A a; includes @PostConstruct, @PreDestroy and
@Resource annotation.
public void setA(A a) {
System.out.println("Setting dependency A of B @PostConstruct defines the callback method post the bean
instance"); initialization.
this.a = a;
} @PreDestroy defines the method to be invoked post the bean
destruction event.
}
<bean id="a" class="mypackage.A"> @Resource wires the bean using name autowiring semantics.
<property name="b" ref="b" />
</bean> What is primary annotation in Spring?
primary annotation sets the bean to get preference when
<bean id="b" class="mypackage.B"> multiple candidates are qualified to auto-wire a single-valued
<property name="a" ref="a" /> dependency.
Spring Bean marked as abstract by abstract=true needs the
corresponding java class be abstract ? @Component
No, not necessarily. A spring bean marked as abstract cannot public class UtilService {
be instantiated, repurpose this bean reference as parent to
other child bean definition.
private UtilRepository utilRepository;
Spring Bean: Specify particular implementation of collection
in your bean definition. @Autowired
<util:set> <util:list> and <util:map> tag specifies the public UtilService(UtilRepository utilRepository) {
collection for the spring bean and the set-class property of the this.utilRepository = utilRepository;
tag specifies the particular implementation of collection class }
you prefer. }

<util:list set-class="java.util.LinkedList"> @Component


Note that util tag has id attribute as well to refer and share public class JdbcUtilRepository implements
with any other bean. UtilRepository {

Spring bean: difference between stateless and stateful beans. public JdbcUtilService(DataSource dataSource) {
stateless beans: beans that are singleton and are initialized
only once. The only state they have is a shared state. These // ...
beans are created while the ApplicationContext is being }
initialized. The SAME bean instance will be returned/injected }
during the lifetime of this ApplicationContext. .
@Primary
@Component Map<String, Repository> beansList =
public class HibernateUtilRepository implements context.getBeansOfType(Repository.class);
UtilRepository {
for (String key : beansList.keySet()) {
public HibernateUtilService(SessionFactory System.out.println(key + " = " +
sessionFactory) { beansList.get(key));
// ... }
} }
} }
What are the attributes of Spring @Transactional annotation?
How to get all the Spring beans implementing a specific Spring transactions take the following properties, propagation
interface? level, isolation, timeout, rollback rules and read-only for
Using ApplicationContext.getBeansOfType method we can any transaction.
retrieve all the beans implementing a specific interface.
When is a spring bean destroy-method being called?
Spring bean destroy method is called when the app-context is
Usage: closed by calling close method or by
ApplicationContext.getBeansOfType(YourClass.class); calling registerShutdownHook method.
package net.javapedia.spring.beanoftype.example;
/Getting application context
import java.util.Map; ApplicationContext appContext = new
ClassPathXmlApplicationContext(beansXMLConfig);
import
org.springframework.context.annotation.AnnotationC //cleaning context
onfigApplicationContext; ( (ClassPathXmlApplicationContext) appContext
import org.springframework.context.annotation.Bean; ).close();
import When is a Spring Singleton bean garbage collected?
org.springframework.context.annotation.Configuratio Singleton beans are created when the Spring container starts
n; and are destroyed when the Spring container stops. The
import reason is spring container always maintains a reference to it
while it is also manually referenced anywhere in your code.
org.springframework.context.annotation.Primary;
When is a prototype bean garbage collected?
@Configuration Spring does only care for the creation and configuration of the
public class AppConfig { prototype bean and then its the responsibility of the user (or
the JVM) to do whatever is necessary.
@Bean
Spring does NOT keep internal references to prototype beans.
public Repository mongoRepository() {
return new MongoRepository(); Explain BeanPostProcessor beans.
} BPP beans are a special kind of beans that get created before
any other beans and interact with newly created beans.
@Bean
To create a bean post processor, implement
@Primary the BeanPostProcessor interface and
public Repository sqlRepository() { implement postProcessBeforeInitialization()
return new SQLRepository(); andpostProcessAfterInitialization() methods.
}
Explain no autowiring mode in spring bean.
public static void main(String[] args) throws no is the default setting which means no autowiring and you
InterruptedException { should use explicit bean reference for wiring.
AnnotationConfigApplicationContext
How do you debug Spring configuration?
context = new
The quick way would be enabling the spring logging in log4j.
AnnotationConfigApplicationContext(AppConfig.class); Add spring appenders to the log4j config either log4j.xml or
log4j.properties.
<category name="org.springframework.beans">
<priority value="debug" />
</category>
Based on the required module, logging could be expanded.Use
either or combination as required.
<category name="org.springframework">
<priority value="debug" />
</category>

<category name="org.springframework.beans">
<priority value="debug" />
</category>

<category name="org.springframework.security">
<priority value="debug" />
</category>
What is component scan in Spring framework?
Component Scan tells Spring the packages containing
annotated classes that should be managed by Spring. If you
have a class annotated with @Controllerwhich is in a
package, if not scanned by Spring, you will not be able to use
it as Spring controller.

Das könnte Ihnen auch gefallen