Spring 5 1st Unit

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Spring is a lightweight framework. It is a framework of frameworks.

It
provides support to various frameworks. It is an open source Java
application development framework which supports developing all types of Java
applications such as enterprise applications, web applications, cloud based
applications and many more. It makes development easier.

Java applications developed using Spring are simple, easily


testable, reusable and maintainable.

Spring modules does not have tight coupling on each other, developer can pick
and choose the modules as per the need for building an enterprise application.

Advantages of Spring Framework:


1. Light weight:
Spring framework is light weight framework because of its POJO (Plain old java
object) model implementation. An PoJo application can be ported from Spring to
another container with little modification.

2. Non-invasive approach:

Spring frame work does not force programmer to inherit API given by spring.
(Application program interface)

3. Loose Coupling:
Because of dependency injection concept, spring objects are loosely
coupled. Spring is LightWeight because of many reasons one being it's
components are loosely couples. For example, you can use Spring JDBC
without Spring MVC.

4. Modular fashion:
Spring framework is designed in modular fashion. A programmer can use only
needed modules and ignore the rest.

5. Easy Testing:
Dependency injection and POJO model makes easy to test an application.

6. Transaction management interface:


Spring framework provides transaction management interface for transaction
management.
7. No need of application server:

Struts or EJB applications requires application server.


Spring application does not require application server.

8. MVC framework:
Spring framework is a alternative to web MVC(Model View Controller)
frameworks like Struts.

9) Predefined Templates
Spring framework provides templates for JDBC(JAVA DATABASE
CONNECTIVITY) , Hibernate, JPA etc. technologies. So there is no need
to write too much code.
Let's take the example of JdbcTemplate, you don't need to write the code for
exception handling, creating connection, creating statement, committing
transaction, closing connection etc. You need to write the code of executing
query only. Thus, it save a lot of JDBC code.

Applications of Spring
Following is the list of few of the great benefits of using Spring Framework −
 POJO Based - Spring enables developers to develop enterprise-class
applications using POJOs. The benefit of using only POJOs is that you do not
need an EJB container product such as an application server but you have the
option of using only a robust servlet container such as Tomcat or some
commercial product.
 Modular - Spring is organized in a modular fashion. Even though the number
of packages and classes are substantial, you have to worry only about the
ones you need and ignore the rest.
 Integration with existing frameworks - Spring does not reinvent the wheel,
instead it truly makes use of some of the existing technologies like several
ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, and
other view technologies.
 Testablity - Testing an application written with Spring is simple because
environment-dependent code is moved into this framework. Furthermore, by
using JavaBeanstyle POJOs, it becomes easier to use dependency injection
for injecting test data.
 Web MVC - Spring's web framework is a well-designed web MVC framework,
which provides a great alternative to web frameworks such as Struts or other
over-engineered or less popular web frameworks.
 Central Exception Handling - Spring provides a convenient API to translate
technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for
example) into consistent, unchecked exceptions.
 Lightweight - Lightweight IoC containers tend to be lightweight, especially
when compared to EJB containers, for example. This is beneficial for
developing and deploying applications on computers with limited memory and
CPU resources.
 Transaction management - Spring provides a consistent transaction
management interface that can scale down to a local transaction (using a
single database, for example) and scale up to global transactions (using JTA,
for example).
Spring Framework module groups:
 Core Container: These are core modules that provide key features of the Spring
framework.
 Data Access/Integration: These modules support JDBC and ORM (Object Relationl
Mapping) data access approaches in Spring applications.
 Web: These modules provide support to implement web applications.
 Others: Spring also provides few other modules such as the Test for testing Spring
applications.

Core container has the following modules:

 Core: This is the key module of Spring Framework . It provides


fundamental support to all other modules. The Core Container consists of the spring-
core, spring-beans, spring-context, springcontext-support, and spring-expression (Spring
Expression Language) modules.
 Bean: This module provides a basic Spring container called BeanFactory. . It allows you
to decouple the configuration and specification.
 Context: This module provides one more Spring container called Application Context. It
inherits the basic features of the BeanFactory container. It provides additional
features to support enterprise application development. It is built on beans and core. The
spring-context-support provides support for integrating common third-party libraries into a
Spring application context.

 Spring Expression Language (SpEL): This module is used for


querying/manipulating object values. The spring-expression module provides a powerful
Expression Language for querying and manipulating an object graph at runtime. The
language supports setting and getting property values, property assignment, method
invocation, accessing the content of arrays, collections and indexers. Spring Framework
5 expression language provides logical and arithmetic operators, named variables, and
retrieval of objects by name from Spring’s IoC container.

 AOP (Aspect Oriented Programming) and aspects: These modules help in isolating
cross-cutting functionality from business logic. An aspect represents a class that
contains advices, join points etc like transaction management. An aspect can be
configured through Spring XML configuration or spring AspectJ integration.

 Java Database Connectivity (JDBC): It provides an abstract layer to support JDBC calls
to relational databases.

 Object Relational Mapping (ORM): It provides integration support for popular


ORM(Object-Relational Mapping) solutions such as Hibernate, JPA, etc.

JMS (Java Messaging System) JMS can be roughly divided into two areas of
functionality, namely the production and consumption of messages.

 Spring OXM stands for Spring Object XML Mappers and it is a module available in
Spring to ease the mapping between java objects and XML documents. The module is
extensible and hence it provides integration with various popular frameworks like Castor,
JAXB, XmlBeans and XStream.
 Transactions: It provides a simple transaction API which abstracts the complexity of
underlying repository specific transaction API's from the application.

Spring Framework provides the following modules to support web application development:

 Web: This module has a container called web application context. It


inherits basic features from ApplicationContext container and adds features to
develop web based applications.
 Webmvc: It provides the implementation of the MVC(model-view-controller) pattern to
implement the serverside presentation layer and also supports features to implement
RESTFUL Web Services.

 WebFlux: Spring 5.0 introduced Spring WebFlux to support Reactive


programming in Spring's web layer. It runs on containers such as Netty, Undertow,
and Servlet 3.1+.

 WebSocket: It is used for 2 way communication between client and server in WebSocket
based web applications.
 Test: This module provides the required support to test Spring applications
using TestNG or JUnit. The Spring Framework provides first-class support
for integration testing in the spring-test module.

Core principles of Spring Framework:

1. Aspect Oriented Programming (AOP).


2. Dependency Injection (DI).

Inversion of Control (IoC)


Inversion of Control (IoC) helps in creating a more loosely coupled application. IoC represents

the inversion of the responsibility. It inverses of application object's creation,


initialization and destruction from the application to the framework.
Now the third party takes care of application object management and dependencies there by
making an application easy to maintain, test and reuse.

There are many approaches to implement IoC, Spring Framework provides IoC implementation
using Dependency Injection(DI).

Spring container managed application objects are called beans in Spring.

We need not create objects in dependency injection instead describe how objects should be
created through configuration.

DI is a software design pattern. It facilitate loose coupling, reuse and ease of testing.

Benefits of Dependency Injection (DI):

 Helps to create loosely coupled application.


 Spring Architecture facilitating re-usability and easy testing.
 Separation of responsibility by keeping code and configuration separately. Hence
dependencies can be easily modified using configuration without changing the
code.
 Allows to replace actual objects with mock objects for testing , this improves
testability by writing simple JUnit tests that use mock objects.

The core container module of Spring framework provide IoC using Dependency Injection.

The Spring container knows which objects to create and when to create through the additional
details that we provide in our application called Configuration Metadata.
1. Application logic is provided through POJO classes.

2. Configuration metadata consists of bean definitions that the container must


manage.

3. IoC container produces objects required by the application using POJO classes and
configuration metadata. IoC container is of two types – BeanFactory and
ApplicationContext.

[POJO in Java stands for Plain Old Java Object. It is an ordinary


object, which is not bound by any special restriction. The POJO file
does not require any special classpath. It increases the readability &
re-usability of a Java program.

Metadata : Data about Data is called metadata ]

Spring provides two types of containers

BeanFactory:

 It is the basic Spring container with features to instantiate, configure and manage the
beans.
 org.springframework.beans.factory.BeanFactory is the main interface representing a
BeanFactory container.

ApplicationContext:
 ApplicationContext is Spring container. It is more commonly used in Spring
applications.
 org.springframework.context.ApplicationContext is the main Interface representing
an ApplicationContext container.
 It inherits the BeanFactory features and provides added features to support enterprise
services such as internationalization, validation, etc.

ApplicationContext is the preferred container for Spring application development. Let us look
at more details on the ApplicationContext container.

org.springframework.context.support.ClassPathXmlApplicationContext is one of the most


commonly used implementation of ApplicationContext.

Example: ApplicationContext container instantiation.

Instantiation of class is called object.

1. Configuration is stored in the config.xml.


2. ApplicationContext container is instantiated by loading config.xml file..
3. Accessing the bean with id "reportService" from the container.

DIFFERENCES between BeanFactory and ApplicationContext containers.

BeanFactory ApplicationContext
Does not support annotation based Dependency Support annotation based Dependency
Injection. Injection.
Support enterprise services such as
Does not support enterprise services.
validations, internationalization, etc.
By default it support Lazy Loading.
By default it support Eager
// Loading BeanFactory Loading.Beans are instantiated during
BeanFactory factory = new load time.
ClassPathXmlApplicationContext (“config.xml
”); // Loading ApplicationContext and
instantiating bean
// Instantiating bean during first access using ApplicationContext context = new
getBean() ClassPathXmlApplicationContext(“config
ReportService reportService = .xm
factory.getBean(”reportService”);

The Spring configuration metadata consists of definitions of the beans.


Spring allows providing the configuration metadata using :

 XML configuration
 Annotation based configuration
 Java based configuration
 In XML configuration, the configuration metadata is provided as a simple XML file
describing bean definitions that the Spring container has to manage.

Basic XML based configuration structure is as follows:


The xmlns attribute specifies the xml namespace for a document.

1. <beans> is the root element & also includes namespace declarations


2. Bean is a definition
3. id attribute represents a unique bean identifier
4. class attribute represents a fully qualified class name
Introduction to Dependency Injection :
we defined ReportService bean as shown below.

<bean id = "reportService" class="com.infosys.demo.ReportService" >

An instance is created and initialized with default values using default constructor.

ReportService reportService = new ReportService();

How do we initialize bean with some specific values


in Spring?
This can be achieved through Dependency Injection in Spring.

Inversion of Control pattern is achieved through Dependency Injection (DI). In Dependency


Injection, developer need not create the objects but specify how they should be created
through configuration.

Spring container uses two Methods to initialize the properties:


Properties are Variables declared in class. It maybe public or private variable.

 Constructor Injection: This is achieved when the container


invokes parameterized constructor to initialize the properties of a class

 Setter Injection: 1) First Default constructer is invoked.

2) Setter Method of a class will initialize properties.

Let us consider the ReportService class of Report Generation application to understand


constructor injection.

 ReportService is a class. It has a property named recordsPerPage. It will modify this


class initialize recordsPerPage property during bean
to
instantiation.

 This is a constructor injection approach.


package com.infosys.service;

public class ReportService {

private int recordsPerPage; // is a property

public ReportService(int recordsPerPage) {


this.recordsPerPage = recordsPerPage;
}
-------------
}

How do we define bean in the configuration to initialize values?


<bean id = "reportService" class ="com.infosys.service.ReportService">
<constructor-arg value = "150"/>
</bean>
package examples;
public class ExampleBean {

// Number of years to calculate the Ultimate Answer


private final int years;

// The Answer to Life, the Universe, and Everything


private final String ultimateAnswer;

public ExampleBean(int years, String ultimateAnswer) {


this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}

Constructor argument type matching


In the preceding scenario, the container can use type matching with simple types if you explicitly
specify the type of the constructor argument by using the type attribute, as the following example
shows:

<bean id="exampleBean" class="examples.ExampleBean">


<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>

Constructor argument index

You can use the index attribute to specify explicitly the index of constructor arguments, as the
following example shows:

<bean id="exampleBean" class="examples.ExampleBean">


<constructor-arg index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean>

You can also use the constructor parameter name for value disambiguation, as the following
example shows:
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg name="years" value="7500000"/>
<constructor-arg name="ultimateAnswer" value="42"/>
</bean>

Setter-based Dependency Injection


The following example is a setter based Dependency injection method.

1) First Default constructer is called


2) Next setter method is called.

public class SimpleMovieLister {

// the SimpleMovieLister has a dependency on the MovieFinder


private MovieFinder movieFinder;

// a setter method so that the Spring container can inject a MovieFinder


public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}

// business logic that actually uses the injected MovieFinder is omitted...


}
The ApplicationContext supports constructor-based and setter-based DI for the beans.

It also supports setter-based DI after some dependencies have already been injected through
the constructor approach.

Constructor-based or setter-based DI?


Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to
setter
use constructors for mandatory dependencies and

methods or configuration methods for optional


dependencies.
The Spring team recommends constructor injection, to implement application components as
immutable objects and ensures that required dependencies are not null.

The constructor-injected components are always returned to the client (calling) code in a fully
initialized state. Setter injection should primarily use for optional dependencies.
Dependency Injection
Dependency injection (DI) is a process whereby objects define their dependencies (that is, the
other objects with which they work)

1.only through constructor arguments


2. arguments to a factory method
4 or properties that are set on the object instance after it is constructed
4. or returned from a factory method.

The container then injects those dependencies when it creates the bean. This process is
fundamentally the inverse (hence the name, Inversion of Control) of the bean itself controlling the
instantiation or location of its dependencies on its own by using direct construction of classes or
the Service Locator pattern.

Code is cleaner with the DI principle, and decoupling is more effective when objects are provided
with their dependencies. The object does not look up its dependencies and does not know the
location or class of the dependencies. As a result, your classes become easier to test,
particularly when the dependencies are on interfaces or abstract base classes, which allow for
stub or mock implementations to be used in unit tests.

DI exists in two major variants: Constructor-based dependency injection and Setter-based


dependency injection.

Constructor-based Dependency Injection


Constructor-based DI is accomplished by the container invoking a constructor with a number of
arguments, each representing a dependency. Calling a static factory method with specific
arguments to construct the bean is nearly equivalent, and this discussion treats arguments to a
constructor and to a static factory method similarly. The following example shows a class that
can only be dependency-injected with constructor injection:

public class SimpleMovieLister {

// the SimpleMovieLister has a dependency on a MovieFinder


private final MovieFinder movieFinder;

// a constructor so that the Spring container can inject a MovieFinder


public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}

// business logic that actually uses the injected MovieFinder is omitted...


}

Notice that there is nothing special about this class. It is a POJO that has no dependencies on
container specific interfaces, base classes, or annotations.

Constructor Argument Resolution

Constructor argument resolution matching occurs by using the argument’s type. If no potential
ambiguity exists in the constructor arguments of a bean definition, the order in which the
constructor arguments are defined in a bean definition is the order in which those arguments are
supplied to the appropriate constructor when the bean is being instantiated. Consider the
following class.

package x.y;
public class ThingOne {

public ThingOne(ThingTwo thingTwo, ThingThree thingThree) {


// ...
}
}

Assuming that the ThingTwo and ThingThree classes are not related by inheritance, no potential
ambiguity exists. Thus, the following configuration works fine, and you do not need to specify the
constructor argument indexes or types explicitly in the <constructor-arg/> element.

<beans>
<bean id="beanOne" class="x.y.ThingOne">
<constructor-arg ref="beanTwo"/>
<constructor-arg ref="beanThree"/>
</bean>
<bean id="beanTwo" class="x.y.ThingTwo"/>
<bean id="beanThree" class="x.y.ThingThree"/>
</beans>

When another bean is referenced, the type is known, and matching can occur (as was the case
with the preceding example). When a simple type is used, such as <value>true</value>, Spring
cannot determine the type of the value, and so cannot match by type without help. Consider the
following class:

Keep in mind that, to make this work out of the box, your code must be compiled with the debug
flag enabled so that Spring can look up the parameter name from the constructor. If you cannot
or do not want to compile your code with the debug flag, you can use the
@ConstructorProperties JDK annotation to explicitly name your constructor arguments. The
sample class would then have to look as follows:

package examples;

public class ExampleBean {

// Fields omitted

@ConstructorProperties({"years", "ultimateAnswer"})
public ExampleBean(int years, String ultimateAnswer) {
this.years = years;
this.ultimateAnswer = ultimateAnswer;
}
}
Core technologies: dependency injection, events, resources, i18n,
validation, data binding, type conversion, SpEL, AOP.

 Testing: mock objects, TestContext framework, Spring MVC


Test, WebTestClient .
 Data Access: transactions, DAO support, JDBC, ORM, Marshalling XML.
 Spring MVC and Spring WebFlux web frameworks.
 Integration: remoting, JMS, JCA, JMX, email, tasks, scheduling, cache
and observability.
 Languages: Kotlin, Groovy, dynamic languages.

Spring Feature Description


Spring JARs are relatively small.

A basic Spring framework would be lesser than 10MB.


Light Weight
It can be deployed in Tomcat and they do not require
heavy-weight application servers.
The application is developed using POJOs.
Non-Invasive
No need to extend /implement any pre-defined
classes.
Spring features like Dependency Injection and Aspect
Loosely Coupled
Oriented Programming help in loosely coupled code.
IoC takes care of the application object's life cycle
Inversion of Control(IoC)
along with their dependencies.
Spring Container takes care of object creation,
Spring Container
initialization, and managing object dependencies.
Aspect Oriented
Promotes separation of supporting f
Programming(AOP)

POJO in Java stands for Plain Old Java Object. It is an ordinary object,
which is not bound by any special restriction. The POJO file does not
require any special classpath. It increases the readability & re-usability of
a Java program.
POJOs are now widely accepted due to their easy maintenance. They are
easy to read and write. A POJO class does not have any naming
convention for properties and methods. It is not tied to
any Java Framework; any Java Program can use it.

https://www.javatpoint.com/pojo-in-java
1)The development team is implementing a banking application, the team wants to
develop logging functionality independently from the main business logic of the application
for better code maintenance. Choose the best Spring feature which helps the team to achieve
this requirement.

Non-Invasive

Spring IoC

Aspect Oriented Programming(AOP) check

DI

AOP supports the separation of cross-cutting functions such as logging, transaction,


and security from the business layer of the application.

Due to Non-Invasive feature of Spring, the developer need not extend any class or
implement any interface exclusively for Spring support and Spring IoC enables
Spring to create objects for developers

2)Which of the following features helps in developing a loosely coupled application in


Spring? [Choose 3 options.]

POJO based programming check


Invasive feature
Dependency Injection check
AOP
Explanation :

Yes, you are right!

POJO classes make application lightweight and help in loose coupling.

Explanation:

Sorry, this is a wrong option.

The Invasive feature mandates the user to implement/extend framework-specific


classes/interfaces making the application tightly coupled. However, the Non-Invasive
feature of Spring prevents the user to extend/implement any class/interface for
Spring support.

Explanation :

Yes, you are right!

Using the Spring IOC, an object’s dependencies are injected rather than creating or
depending on other objects. However, there are other options, which are also right.

3)Which of the following statements are TRUE about Spring? [Choose 2 options.]

Spring is an open source Java application development


framework check
Spring can be used to implement a standalone Java application
It is mandatory to include all the Spring modules jars for building any kind of Java
application
Spring is used to implement only the business logic of an application
Explanation :

Yes, you are right!

Spring is an open-source framework.

Explanation:

Sorry, this is a wrong choice.

The Spring Framework modules are organized as loosely coupled modules, the
developer can choose modules based on the need by adding the corresponding Jars.

Q1 of 3outlined_flag
The development team needs to implement a Spring application with the data access layer to
perform the required database operations. Which of the Spring modules given below can be
best used to achieve this requirement? [Choose 2 options].
Web (Web module provides support to create web-based applications.)
Core
ORM
Aop

explanation :

Correct Answer!

The core module is the base module in the spring framework on which all other
modules of the framework are dependent. Therefore, the development team needs
this module to achieve the requirement.
Correct Answer!
ORM module of Spring Data Access Layer provides integration support for ORM solutions.

Q2 of 3outlined_flag
An online shopping web application has to be developed with the data access layer to get
item details. Which Spring modules can be best used to implement this application? [Choose
3 options.]

Web
Core container
Data Access modules - JDBC/ORM
Test

Explanation :

Correct Answer!

Web module provides support to create web-based applications. Therefore, to


develop any web-based application this module is required.

Explanation :

Correct Answer!

Data Access module provides different data access approaches. Therefore, to


develop a data access layer of spring application this module is required.

Correct Answer!

Web module provides support to create web-based applications. Therefore, to


develop any web-based application this module is required.

Q3 of 3outlined_flag
A Banking application business layer has been developed using Spring Core and AOP
modules, data access layer using Spring Data Access/Integration module. The development
team wants to implement the presentation tier of the application using simple Model-View-
Controller architecture. Can you suggest the best Spring modules to support this requirement?
[Choose 2 options.]

websockets
aspects
webmvc
web
Explanation :
Yes, you are right!
This module provides an implementation of MVC (model-view-controller) pattern and
extends its support to implement RESTful Web Services. So, it can support the development
of the presentation tier.

Yes, you are right!

This module extends the Application Context and provides a Web-oriented


Application context. So, this module is needed to develop the presentation tier of the
application.

Sorry, this is a wrong choice.

Aspects module helps in isolating crosscutting functionality. Therefore, the


development team may not need this module’s support to develop its presentation
tier.

Q1 of 3outlined_flag
The development team needs to implement a Spring application with the data access layer to
perform the required database operations. Which of the Spring modules given below can be
best used to achieve this requirement? [Choose 2 options].
web
Core
ORM
aop
Explanation :

Correct Answer!
The core module is the base module in the spring framework on which all other modules of
the framework are dependent. Therefore, the development team needs this module to achieve
the requirement.

Explanation :

Correct Answer!
ORM module of Spring Data Access Layer provides integration support for ORM solutions.
Q2 of 3outlined_flag
An online shopping web application has to be developed with the data access layer to get
item details. Which Spring modules can be best used to implement this application? [Choose
3 options.]

Web
Core container
Data Access modules - JDBC/ORM check
Test
Explanation :

Correct Answer!
The core container is the base of Spring framework and all other modules are built on top of
it. Therefore, to develop any Spring based application this module is required. However,
there are other options, which is also right.

Explanation :

Correct Answer!
Data Access module provides different data access approaches. Therefore, to develop a data
access layer of spring application this module is required.
Yes, you are right!
Web module provides support to create web-based applications. Therefore, to
develop any web-based application this module is required.

A Banking application business layer has been developed using Spring Core and AOP
modules, data access layer using Spring Data Access/Integration module. The development
team wants to implement the presentation tier of the application using simple Model-View-
Controller architecture. Can you suggest the best Spring modules to support this requirement?
[Choose 2 options.]

websockets
aspects
webmvc
web
Explanation :

Yes, you are right!


This module provides an implementation of MVC (model-view-controller) pattern and
extends its support to implement RESTful Web Services. So, it can support the development
of the presentation tier.

Explanation :

Yes, you are right!


This module extends the Application Context and provides a Web-oriented Application
context. So, this module is needed to develop the presentation tier of the application.

Q1 of 3outlined_flag
Consider a MobileService class in the package com.infosys with appropriate properties and
methods.
A Spring configuration file defining a bean of MobileService class is shown below:
<bean id="mobileService" class="------------"/>
What should be the value of the class attribute of <bean> tag?

com.infosys

com.infosys.MobileService
MobileService

com.infosys.MobileService.class
Explanation :

Yes, you are right!


Value for the class attribute in the bean declaration should be the fully qualified class name.
com.infosys or MobileService can't be used because they are not the fully qualified name of
the class.
com.infosys.MobileService.class shouldn't be used because the fully qualified name of the
class should be specified and not the class itself.
Q2 of 3outlined_flag
Consider a MobileService class in the package com.infosys with appropriate properties and
methods.
A Spring configuration file defining a bean of MobileService class is shown below:
<bean id="mobileService1" class="com.infosys.MobileService"/>
<bean id="mobileService2" class="com.infosys.MobileService"/>
Select the CORRECT statement from the following options?

Spring does not allow multiple bean definitions of same class

Creates two beans mobileService1 and mobileService2 of


type MobileService class, which can be accessed in
application by using the id of the respective bean
Creates only one bean in the container of type MobileService class

Spring does not allow more than one bean definition in the configuration
Explanation :

Yes, you are right!


Two beans of MobileService class will be created and registered with the Spring container
and beans can be accessed using their ids respectively.
Any number of beans can be defined and created in a configuration file, Spring creates as
many beans as specified in the configuration file, and in this case, Spring does not create one
bean as two beans are specified in the configuration file.
Q3 of 3outlined_flag
Consider the GreetingService class given below:
package com.infosys.service;
public class GreetingService {

private String greeting ;

public String getGreeting() {


return greeting;
}

public void setGreeting(String greeting) {


this.greeting = greeting;
}

}
A Spring configuration file(config.xml) defining bean of the GreetingService class is shown
below:
<bean id = "greetingService" class = "com.infosys.service.GreetingService"
/>
The main method of the application includes the following statements:
ApplicationContext context = new
ClassPathXmlApplicationContext("config.xml");
GreetingService greetingService = (GreetingService)
context.getBean("greetingService");
greetingService.setGreeting("Hi, Welcome to Spring Course!!");
System.out.println(greetingService.getGreeting());
What will happen when we execute the above main method?

Displays the greeting message "Hi, Welcome to Spring


Course! !"
Displays null as the greeting property is not initialized
POJO class setter method cannot be invoked on the bean
Explanation :

Yes, you are right!


Before attempting to print the greeting property of GreetingService class it is initialized with
"Hi, Welcome to Spring Course! !" using the setter method.
Null is not displayed as the bean is initialized using the setter method and setter method can
be invoked on a POJO class

You might also like