0% found this document useful (0 votes)
7 views

Spring Short Notes

Uploaded by

tmdjgs7zjq
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Spring Short Notes

Uploaded by

tmdjgs7zjq
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 18

Spring

=====================================

(1) What is Spring Bean ?

- Every class we are writing in spring application can be called as Spring Bean.

(2) What is Dependency ?

- Any property available in a Bean class which needs to be initialized


is called as Dependency.

(3) What is Injection ?

- Initialization of Bean class property is also called as called as Injection.

(4) What is Dependency injection (DI) ?

-The process of initializing bean dependencies is called as Dependency Injection.

(5) What are types of Dependency Injection supported by Spring ?

- Spring Depedency Injection uses 3 ways to inject the dependencies


(a)Setter Injection (b) Constructor Injection (c) Field Injection (Using
Annotations- @Autowired)

(6) What is Setter Injection ?

- The process of initializing Bean dependencies with setter methods is


called as Setter Injection.

(7) How can I implement Setter Injection ?

- Using <property> tag.

(8) What is Constructor Injection ?

- The process of initializing Bean Dependency with Constructor is called


as Constructor Injection.

(9) How can I implement Constructor Injection ?

- Using <constructor-arg> tag.

(10) What is Bean Defination ?

- Configuring Bean and its dependencies in Spring Configuration document


is called as Bean Defination.

(11) when should i use <property> tag and <constructor-arg> tag ?

- With Setter Injection and Constructor Injection.

(12) When should I use value attribute and ref attribute ?

- Primitive Variables, Wrapper Variables, String Variables.


Use ref attribute for specifying bean references for reference type
variables.
(13) What are the GOF Patterns used in Spring IOC Container?

- Single-ton pattern and Factory pattern.

(14) What is Spring Container ?

- ApplicationContext object is called as Spring Container.

(15) What will be done by the Spring Container when it finds following bean
definition?

Ans:
<bean id="aobj" class="com.jkindia.spring.A "> .
<property name="a" value="99" />
<property name="msg" value="Hello Guys"/>
</bean>
A aobj=bew AO;
aobj.setA(99);
aobj.setMsg("HelloGuys");

(16) What will be done by the Spring Container when it finds following bean
definition?
<bean id="bobj" class="com.jlcindia.spring.B">
<constructor-arg value="88" />
<constructor-arg value="Hai Guys"/>
</bean>

Ans: B bobj=new 8(88,"Hai Guys");

(17) What will be done by the Spring Container when it finds following bean
defination?

<bean id="hello" class="com.jlcindia.spring.Hello">


<property name="aobj" ref="aobj"/>
<consrructor-arg ref="bobj"/>
</bean>

Ans: Hello hello=new Hello(bobj);


hello.setAobj(aobj);

(18) What is Spring Configuration file ?

Ans: Spring Configuration file is an XML file which contains various bean
definitions.

(19) what will happen with the following code ?


<bean>
<bean id="hello" class="com.jlc.Hello"/>
</bean>
Hello hello=(Hello)ctx.getBean("hello1");

Ans: Exxception will be raised- NoSuchBeanDefinationException: No bean


named 'hello1' is defined

(20) Can I cinfigure two beans with same Id ?


<bean>
<bean id="hello" class="Hello1" />
<bean id="hello" class="Hello2"/>
</bean>

Ans: No, Bean Id must be unique.


Error: There are multiple occurrences of ID value 'hello'

(21) Can I configure two beans with same Bean class?

Ans: Yes.
<beans>
<bean id="hello1" class="com.Hello"/>
<bean id="hello2" class="com.Hello"/>
</beans>

Hello h1=(Hello)ctx.getBean("hello1");
Hello h2=(Hello)ctx.getBean("hello2");

Here h1!=h2

(22) What will happen with the following code ?

<beans>
<bean id="hello" class="com.Hello">
<constructor-arg value="99"/>
</bean>
</beans>

class Hello{
int x;
// No constructor
}

Ans: BeanCreationException:Error creating bean with name 'hello'


defined in class path resource [jlcindia.xml]: Could not resolve
matching constructor.

(23) What will happen with the following code ?

<<beans id ="hello" class="com.jlc.Hello">


<property name="x" value="99" />
</bean>
</beans>

class Hello{
int x;
//No setter
}

Ans: NotWritablePropertyException: Invalid property 'x' of bean class


[A]: Bean property 'x' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter ?

(24) How many bean scopes are there?

Ans: Bean Instance created by Spring Container can be in one of the following
Scopes.
(a) singleton (b) prototype (c) request (d) session (e) global-session

• Usage:
With XML Config:
<bean id="" class="" scope=""/>

With Java Config:


@Scope(value="")

(25) What is default bean scope?

Ans: singleton is the default scope in the ApplicationContext container.

(26) What is the difference between singleton and prototype?

Ans: singleton:
------------

• When bean scope is singleton then only one instance will be created for that bean
and the same instance will be returned when you call getBean() method.
• singleton is the default scope in the ApplicationContext container.
• When scope is single-ton then default loading type is aggressive loading.

prototype
---------

• When bean scope is prototype then every time a new instance will be created for
that bean when you call getBeanO method.
• When scope is prototype then default loading type is lazy loading.

(c) request : request scope HttpServletRequest in the web apphcation.

(d) session : session scope is equals to HttpSession in the web application.

(e) global-session : global-session scope is equals to session in the


web application.

(27) How many bean loading types are there?

Ans: Beanconfigured in the Spring Context.xml can be loaded in two ways.


(a) Aggressive loading or Eager loading
(b) Lazy loading

Usage :
With XML Config :
<bean id="" class="" scope="" Jazy-init=""/>

With Java Contig:


@Lazy(value="")

(28) What is default bean loading type?

Ans: Lazy Loading

(29) What is the difference between Lazy loading and Aggressive loading ?

Ans:
(a) Aggressive loading or Eager loading
----------------------------------------------
In the case of aggressive loading, all the Beans will be loaded, instantiated and
initialized by the container at the container start-up.
<bean id="" class="" scope="" Jazy-init="false"/>

(b) Lazy loading-

In the case of lazy loading, all the Beans will be loaded, instantiated and
initialized
when you or container try to use them by calling getBean() method.
<bean id="" class="" scope="" lazy-init="true" />

Answer the following questions based on Labl.

(30) What will happen with the following?

<bean id="ao" class=" ....A">


...
</bean>

<bean id="bo" class=" ....B">


...
</bean>
<bean id="hello" class=".... Hello">
...
</bean>

Ans:
All 3 beans will be loaded at container start-up and all are singletons.
Order of loading: A-B-Hello

31) What will happen with the following ?

<bean id="ao" class="...A" lazy-init="true">


...
</bean>

<bean id="bo" class="...B" lazy-init="true">


...
</bean>

<bean id="hello" class="...Hello" lazy-init="true">


...
</bean>

Ans:
No bean will be loaded at container start-up.
All are Singleton
Loads when you call getBean() method
Order of loading: B, Hello, A

(32)What will happen with the following ?

<bean id="ao" class="...A" lazy-init="true">


...
</bean>

<bean id="bo" class="...B" lazy-init="true">


...
</bean>
<bean id="hello" class="...Hello" lazy-init="false">
...
</bean>

Ans:
All 3 Beans will be loaded at container start-up.
All are Singletons
Loads when you call getBean() method
Order of loading: B, Hello, A

(33)What will happen with the following ?

<bean id="ao" class="...A" lazy-init="false">


...
</bean>

<bean id="bo" class="...B" lazy-init="false">


...
</bean>

<bean id="hello" class="...Hello" lazy-init="true">


...
</bean>

Ans:
2 beans will be loaded at container start-up and all are singletons.

(34)What will happen with the following ?

<bean id="ao" class="...A" lazy-init="false" scope="prototype">


...
</bean>

<bean id="bo" class="...B" lazy-init="false" scope="prototype">


...
</bean>

<bean id="hello" class="...Hello" lazy-init="true" scope="singleton">


...
</bean>

Ans:
No Beans will be loaded at container start-up.
A,B are prototype.
Hello is singleton.

(35)What will happen with the following ?

<bean id="ao" class="...A" scope="prototype">


...
</bean>

<bean id="bo" class="...B" scope="prototype">


...
</bean>

<bean id="hello" class="...Hello" scope="singleton">


...
</bean>

Ans:
All 3 Beans will be loaded at container start-up.
A,B are prototype.
Hello is singleton.
Order of loading: B, Hello, A

(36) What is wiring ? How many ways are available ?

Ans: Wiring is the process of injectingthe dependency of the Bean.


Wiring can be done in two ways.
(a) Explicit wiring
(b) Implicit wiring or Auto wiring

(a) Explicit wiring :

In the case of explicit wiring you have to specify the bean Dependencies
explicitly the container will inject those Dependencies.

<beans>
<bean id="ao" class="A"/>
<bean id="bo" class="B"/>

<bean id="hello" class="Hello">


<property name="aobj" ref="ao"/>
<property name="bobj" ref="bo"/>
</bean>
</beans>

(b) Implicit wiring or Auto wiring :

In the case of Auto wiring Spring Container can detect the Bean Dependencies
automatically and injects those Dependencies.

<beans>
<bean id="ao" class="A"/>
<bean id="bo" class="B"/>
<bean id="hello" class="Hello" autowire="xxx"/>
</beans>

Following are possible values for autowire attribute


(a1) byName (a2) byType (a3) constructor

(a1) byName
-------------

When autowire attribute value is byName then Spring Container checks whether
any bean instance running in the Container whose name(or id) is same as bean
property(variable) name or not

When bean is found with the matching name then it will be injected otherwise bean
property remains uninjected.

Bean will be instantiated using Default constructor.


Dependent Bean Instances will be injected through setter injection only.

(a2) byType
---------
When autowire attribute value is byType then Spring Container checks
whether any bean instance running in the container whose Type is same
as bean property data Type or not.

.Bean will be instantiated using Default constructor.


.Dependent Bean Instances will be detected using bean data type.
.detected bean instances will be injected through setter injection only.

(a3) constructor :
--------------------

. When autowire attribute value is constructor then Spring Container checks


whether any bean instance running in the Container whose Data Type is same as
bean property Data Type or not.
. Depending on the Availability of Bean Instances, Spring Container Identifies the
Matching Constructor and invokes that Constructor to inject the Bean
Dependencies.
. Bean will be instantiated using matching constructor.
. Dependent Bean Instances will be injected through constructor injection.

(58) How can i implement Annotation Based Autowiring ?

Ans: Using the following 3 Annotations


@Autowired , @Resources , @Inject

(59) Annotations are replacement for XML but still we are writing Beans
in xml only. Can i use only annotations without xml ?

Ans: Yes, You can configure your Beans with Java Based Configuration without XML
Configuration.
Use the following Annotations for Java Based Configuration
@Configuration
@Bean

(60) What is the use of @Scope Annotation?

Ans: @Scope indicates the name of a scope to use for the instance returned from the
method.

(61) What is the use of @Lazy Annotation?

Ans: @Lazy annotation indicates whether a bean is to be lazily initialized.

(62) Can I use cyclic Dependency Injection ?

Ans: Depending on the case.


When You are injecting the resources with Setter injection then
circular reference is allowed.
. When you are injecting the resources with Constructor injection
then circular reference may be allowed or may not.

(66) What is P-NameSpace & C-NameSpace ?

Ans:. In the Spring framework, p-namespace is used to inject


setter-based dependency. The p-namespace is XML shortcut and
reduce the numbers of line in the configuration file. However,
the p-namespace is not defined in an XSD file and exists
only in the core of Spring.
. The c-namespace in Spring enables you to use the bean element's attributes
for
configuring the constructor arguments.

(67) How can I implement Annotation Based Auto wiring?

Ans: When you want to use the Annotations, You need to do the following.
(a) You must enable context namesp:ace
(b) Add <context:annotation-config/>

.Now you can use @Autowired annotation for the beans.

class Hai {}
class A{}
class Hello{

@Autowired
A aobj;
@Autowired
Hai hai;

<bean id="ha" class=" .... Hai" />


<bean id="ao" class=" .... A" />
<bean id="hello" class=" .... Hello"/>

(68) What is difference between @Autowired and @Resoueces ?

Ans: @Autowired is a spring annotation whereas @Resource is


specified by the JSR-250. So the latter is part of normal java where as @Autowired
is only available by spring.

(69) Can I use Annotation directly in Spring Application ?

Ans: No.

(70) How to decide to the type of Dependency Injection ?

Ans: Setter Injection or Field Injection -> Make the beans loosly coupled
Constructor Injection -> Make the beans tightly coupled

(71) How can i resolve Compile time polymorphism with constructor Injection ?

Ans: Depending on the Availability of the resources and Constructors.

(72) Can I use P-Namespace with constructors?

Ans: No

(73) What is the bean name?

Ans : Bean id is also called as bean name.


You can also specify the name for the bean in the bean definition.
(77) How can I implement Annotation based Autowiring ?

Ans: Using the following 3 Annotations -> @Autowired , @Resource , @Inject

(78) What is difference among @Autowired , @Resource and @Inject ?

Ans: The main difference is that, @Autowired and @Inject works


similar for 100% without any differentiation. These two
annotations using AutowiredAnnotationBeanPostProcessor to
inject dependencies. But,@Resource uses
CommonAnnotationBeanPostProcessor to inject dependencies and
there is difference in the order of checking.

(79) What is the use of <Import> tag ?

(80) What is the use of @Import Annotation ?

(81) What is the use of @ImportResource Annotation ?

(82) What is the use of @Scope Annotation ?

(83) What is the use of @Lazy Annotation ?

84) What are the lntialization callbacks provided with


BeanFactory container?

(85) What are the lntialization callbacks provided with ApplicationContext


container ?

(86) You can Inject the required resources with D.I ? What is the use of
Initialization callbacks?

Ans: Mainly to check whether resources are initialized by the Spring Container or
not.

class Hello{
@Autowired
Hai hai;

@PostConstruct
public void initO{
if(hai==null){
hai= ..... ;
} else {
throw Some Exception;
}
}
void showO{
hai.m1();
}
}

(87) What are the Disposable callbacks provided with BeanFactory


Container ?

(88) What are the Disposable callbacks provided with ApplicationContext


Container ?

(89) How can I get the reference of BeanFactory container into bean?

Ans: There are two ways to initialize your bean with BeanFactory reference.
(A) By implementing BeanFactoryAware interface and overriding
setBeanFactory() method.
(B) By using @Autowired (use this)

(90) How can I get the reference of ApplicationContext container


into the bean?

Ans: There are two ways to initialize your bean with ApplicationContext
reference.

(A) By implementing ApplicationContextAware interface and overriding


setApplicationContext() method.
(B) By using @Autowired (Use this)

(91) What is the use of BeanPostProcessor?

Ans: BeanPostProcessor allows to extend the functionality of ApplicationContext


container.
Consider the following case:

You want to make jlc() method as lifecycle method for every bean
-----------------------------------------------------------------

jlc() method has to be called when bean class

• is implementing JLC interface.


• is containing the method which is marked with @JLC.

(A) Bean class Implementing JLC interface.

class Hello imp JLC, lnitializingBean{


public void jlc() {
// do some thing.
}
}

public class MyBeanPostProcessor implements BeanPostProcessor {


public Object postProcessBeforeInitialization(Object object, String bname){
// 1. get Object of the Bean
//2. get the List of interfaces implemented by the Bean class using Reflection.
//3. Check the JLC interface in that list
//4. if JLC interface is in the List

then call jlc() method


}
...
}

(B) Method in the Bean class marked with @JLC


-------------------------------------------------

class Hello imp InitializingBean {


@JLC
public void jlc(){
// do something
}
}

public class MyBeanPostProcessor implements BeanPostProcessor (


public Object postProcessBeforelnitialization(Object object, String bname}{
//1. get Object of the Bean
//2. get the List of methods available in Bean class using Reflection.
//3.Check whether any method is marked with @JLC.
//4.lf@JLC is found for any method
then call that method
}
}

(92) What are the Spring Containers supported?

Ans: The Spring container is at the core of the Spring Framework.


The container will create the objects, wire them together,
configure them, and manage their complete life cycle from
creation till destruction. The Spring container uses DI to
manage the components that make up an application.

There are two types of Container


---------------------------------
(1) BeanFactory Container (old).
(2) ApplicationContext Container (new).

(A) BeanFactory Container


You can create the BeanFactory Container as follows.
. Resource res=new ClassPathresource("jlcindia.xml");
OR
. Resource res = new
FileSystemResource("D:/D1/Spring/Labs/l0C/Lab21/src/jlcindia.xml");

. BeanFactory factory=new XmlBeanfactory(res);

(B) ApplicationContext Container


-----------------------------------------------------------
. ApplicationContext interface has three concrete implementations.

(a1) ClassPathXmlApplicationContext (a2) FileSystemXmlApplicationContext


(a3) XmlWebApplicationContext
. We can create the ApplicationContext Container as follows.

- ApplicationContext ctx=new ClassPathXmlApplicationContext("jlcindia.xml");


- ApplicationContext ctx=new
FileSystemXmlApplicationContext("D:/D1/Spring/Labs/l0C/Lab21/src/jlcindia.xml");

Life of Bean in the ApplicationContext container


----------------------------------------------------
(1) Container loads the Bean class into memory.
(2) Container creates the Bean instance by using corresponding constructor
(Constructor injection)
(3) Bean dependecies will be injected with the following ways

a . Annotation based Auto Wiring.(Filed injection) ,


b . XML based Explicit Wiring (Setter Injection)
c . XML based Auto Wiring (Setter Injection)
(4) When bean class is implementing BeanNameAware interface then setBeanName()
method will be called by the container.
(5) When bean class is implementiug BeanFactoryAware interface then
setBeanfactory() method will be called by the container.
(6) When bean class is implementing ApplicationContextAware interface then
setApplicationContext() method will be called by the container.
(7) When BeanPostProcessor is registered then postProcessBeforelnitialization()
method will be called by the container.
(8) When any method is found with @PostConstruct annotation then that method will
be called.

(9) When bean class is implementing lnitialingBean interface then


afterPropertiesSet() method will be called by container.
10) When bean defintion contains init-method attribute then that specified method
will
be called.
(11) When BeanPostProcessor is registered then postProcessAfterlnitialization()
method will be called by the container.
(12) Fully initialized Bean instance will be ready to use in the ApplicationContext
container.

(93) What are the difference between BeanFactory and ApplicationContext Container?

(94) We are creating Spring container object in main method after scope over still
container
objects exits. How to justify ( Every object should be inside scope).

Ans: If container is shutdown then it has to invoke disposable callbacks.

(95) Is there any relationship between BeanFactory and ApplicationContext


container?

Ans: ApplicationContext is the decorator of Bean Factory.

ApplicationContext = BeanFactory + Extra code

ApplicationContext creates the instance of BeanFcatory internally.

(96) Why we are using AbstractApplicationContext?


Ans: Only to invoke the method registerShutdownHook()

(97) Why we are using AnnotaionConfigurationApplicationContcxt ?

Ans : To use Java Based Configuration

(98) How Can I decide to use type of Spring container?

Ans: Use always ApplicationContext only.

(99) Is there any way to extend the BeanFactory container functionality?

Ans: No

(lOO) Can I clone Application Context object?

Ans: No No No

(101) Can I inject the Bean with One scope into another Bean with different scope?

Ans: Yes

(102) Can I mark two methods with @PostConstruct annotation?

Ans: Yes , we can

(103) Can I mark two methods with @PreDestroy annotation?

Ans: Yes , you can

(104) Can I inject the Bean defined one xml into another bean defined in another
xml?

Ans: Yes

(105) What are Inner Beans ?

Ans: When you specify the Bean defination inside another


defination then it is called as Inner Bean.

<bean id="hai" class=" .... Hai" / >


<bean id="hello" class=" .... Hello">
<property name="hai" ref="hai" / >
</bean>

With Inner Beans:


------------------
<bean id="hello" class="Hello">
<property name="hai">
<bean class="Hai"/>
</property>
</bean>

(106) What is the difference between ClassPathResource and FileSystemResource ?

Ans:

(107) What is the difference between ClassPathXmlApplicationContext


and FileSystemXmlApplicationContext ?

Ans:

(108) What is the sub class of BeanFactory inteface ?

Ans:

(109) What are the sub classes of ApplicationContext interface?

Ans:

(110) What is the use of @Required Annotation ?

Ans:

(111) What is the difference between @Autowired(required=true) and


@Autowired(required=false) ?

Ans:

(112) What is the use of @Qualifier Annotation ? Where can


I use this ?

Ans:

(113) What are the GOF Patterns discussed in Spring IOC ?

Ans: (a) Singleton Pattern (b) Factory Pattern (c) Decorator Pattern

(114) While you are configuring the beans in xml, we are hard-coding the values?
Can I make
it dynamic?

Ans: Yes, You can use property files.( using Externalizing Bean properties)

(115) What is the use of ApplicationEvents?

Ans: Refer Notes

(116) How Can I Implement ApplicationEvents?

Ans: Refer Notes

(117) How Can I Publish ApplicationEvents?

Ans: Refer Notes

(118) HoW Can I Implement ApplicationListeners?

Ans: Refer Notes

Ql 19) HoW Can I Register ApplicationListeners?

Ans:

Q120) Can I Register multiple ApplicationListeners with the Spring Container ?

Ans: Yes
(121) What is the Use of Property Editors?

Ans:

(122) How Can I develop custom property Editors?

Ans:

(123) How Can I Register Custom Property Editors?

Ans: Refer Notes

(124) How Can I Register Message Bundles?

Ans : Refer Notes

(125) How Can I Access the properties from Message Bundles?

Ans: Refer Notes

(126) Why I need to Inject ApplicationContext into the Bean?

Ans: You can use the following methods of ApplicationContext.

getMessageQ
publishEvent()
etc

(127) What is main goal of AOP ?

Ans: AOP is new kind of Programming technique which is mainly


used to make the clean separation between commonaly required
middle level services and core business logic of the application.

(128) What are ways available to implement AOP?

Ans:

(129) What is Aspect ?

Ans:

(130) What is Advice ?

Ans:

(131) What is JoinPoint ? what sre the Join Points supported


in Spring AOP ?

Ans:

(132) What is PointCut? How to define PointCuts in Spring API based AOP ?

Ans:

(133) What is the syntax to define Aspect Pointcut Expression?

Ans:
(l34) Write the AspectJ pointcut Expression for invoking any
any method from any business service ?

Ans : execution(**** (..))

(135) Write the AspectJ point Expression for invoking the methods starting with add
from any business service?

Ans: execution(* *Service.add*(..))

(l36) What is an Advisor? How to define Advisor in Spring API Based AOP?

Ans :

(l37) What is the difference between Target Object and Proxy Object?

Ans :

(l38) What is Weaving?

Ans : Refer Notes.

(139) What are the ways a vailable to implement Proxying?

Ans:

(l40) What is Explicit Proxying?

Ans :

(141) What properties has to be configured with ProxyFactoryBean when you are using
Class Model?
Ans : You need to configure the following three properties:
1 )targetClass
2)target
3)interceptorNames

(142) What properties has to be configured with ProxyFactoryBean when you are using
interface Model?

Ans : You need to configure the following three properties:


1)proxylnterfaces
2)target
3)interceptorNames

(143) What is Autoproxying ?

Ans:

(144) How proxy object works?

Ans:

(145) How can I implement AOP using AOP API?


Ans : Using API
MethodBeforeAdvice -before()
AfterRerurningAdvice -afterReturing()
ThrowsAdvice -afterThrowing()
(146) How can I implement AOP using Annotation Support?

Ans : Using Annotation based AOP(2.0):

@Aspect @PointCut @Before @AfterReturning


@AfterThrowing @After @Around

(147) How can I implement AOP using Schema Support?

Ans : You must enable aop namespace to use the following tags.
<aop:config> <aop:aspect> <aop:pointcut>
<aop:before> <aop:after-returning> <aop:after-throwing>
<aop:after> <aop:around>

(l48) What is the use of ProceedingJoinPoint?

Ans: Refer Notes.

(149) What is the difference between @AfterReturning and @After ?

Ans : Refer Notes.

(150) What is the use of @Aspect annotation.

Ans:

(151) What are GOF design Patterns discussed in AOP?

Ans: Proxy - used heavily in AOP

===================================================================================
=================================================

Spring MVC based project


==============================

You might also like