Public Class: Singleton, Prototype, Request, Session and Global Session
Public Class: Singleton, Prototype, Request, Session and Global Session
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.
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.
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. }
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.