KA)
0.2KB/s © @ “ull Guat GD
POM Maier Kool) ©
«Page 1013» Service Layer nvaducton
‘The service layer of an enterprise application is the ayer in which the business logic is implemented, tis
the heart of enterprise applications as it contains the business processes of the application. It interacts
with the presentation layer and the persistence layer. In this course, you will learn the development
of service layer of enterprise applications using Spring Boot,Eva 4.2KB/s ©
ray @ lex.infosysapps.com
B+ 4 pape 2 013 5 Dereepngsenee aye
In this course, you will understand the concepts of Spring Boot and service layer by developing @ banking
‘application named InfyBank containing multiple medules. One of the modules of this application is the
Customer module and one of the mast common feature of any application and also this application is
that the customer should be able fo login to the application using valid credentials,
To login, the business logic is to validate the credentials entered by the customer against the details
stored in the database. On successful validation, the customer should be alowed to use the application
If credentials are invalid, error page should be displayed
‘To implement this functionality of login, the folowing classes need to be implemented in the application:
“+ Userinterface ~ The customer will interact with the application using web-based user interface.
‘This interface wil interact with the CustomerLoginControler class. In this course, for simplicity, the
Web interface wil be replaced with this class,
‘+ CustomerLoginController - This class wil interact with the user interface and the
CustomerLoginServicelmpl class of service layer.
+ CustomerLoginServicelmpl - The business logic will be implemented in this class. It will interact,
withthe CustomerLoginController of the presentation layer and CustomerLoginRepositoryipl
of the persistence layer.
«+ CustomerLoginRepositoryimpl ~ This class is a persistence layer class and will interact with the
database and Customerl oginServiceimpl class of service layer.
‘+ CustomerLoginDTO ~ This is a DTO (Data Transfer Object) class which is used to transfer data
across different layers,
\When the customer enters the login credentials, the data will low from CustomerLoginContraller to
CustomerLoginServicelmpl and then to Customer oginRepositoryimp! class as follows:
Let us now quickly see the implementation of these classes.= 4 Page _3_of9 + Serco Layerimplementtion
‘The implementation ofthe various classes are as fotos:
1. CustomerLoginDTO class
ot
eC
ETS ee
pense Ty
eae:
forces ress
pest
eer
Hashilapestring, String>Q
Ce Seer Ti
Nrape rere tt
jentials.put(
Pare eter ti
poate es)
rere e ss)
In this class, data has been stubbed for ease of learning. In actual implementation, this class will cantain
the code for interacting withthe database
4. CustomerLoginServce interfaceI 41.7KB/s ©
ray @ lex.infosysapps.com
€ [e* _introduction to Service Layer
In this class, data has been stubbed for ease of learning. In actual implementation this o
cade for interacting with the databas
ustomerLoginService interface
eu meart
Cou e
Seam
i Eraser age
om
NOTE: InfyBankes
eee
Cer
eas
Peeters
sy
Pree eat
roe Sst eae
Sree o La i
toReturn =
Pes cesta
o
Pee csc
et ght oes age teen ae ser see
eer Ran tee eRe eer esc ee
Potty
aes
Cre?
pee eeeens ta
Co eneaySKE)
0.2KB/s ©
(OMe Mane) cxeo)
coat ice)
6 Customer
CU
Coeur
tee
ets
ety
Estes
Ott)
eerste
+
n
7. Userintertace cla
‘The customer interacts with the appl
ustomerLoginContioler cla
comCet
er
ee
oor
pies
TIC?
Cree
org
On
4
o
rege erticobet
Crcerstrerterobcy
n
icc ences eee
}
ee aster
Cos Etre recy
Ceeetrsoy
aed
fi
Precast
erat
4
esta
Cereal
ation using a web user interface. The web interface interacts with
F simplicity, the web interface is replaced with the following
Cou TSC
Seeerso
Tocca
)
axe oro)
config
eed )
ieee Ta)
ree era}
prem ertoic)
cere sa
a
oO
authenticateCustoner (custonerLoginbTO)
LOGGER. info config. getProperty(message))
ri Crsto
ty(exception. getlessage()))7.7KB/s © B “ull
com/en/viev ©
fe
Consider the folowing implementation of CustomerLoginServicelmpl class:
Dare
ee
In this implementation, CustomerLoginServicelmp! depends on CustomerLoginReposttory. It also
instantiates CustomerLoginRepositorylmp! class which makes it'_—‘tightly coupled
with CustomerLoginRepositoryimpl class. This isa bad design because of the following reasons:
1.1 you want to unit test authenticateCustomer) method, then you need a mock object of
CustomerLoginRepository but you cannot use mock object because there is no way to substitute the
CustomerLoginRepositoryimp! object that CustometLoginServicelmal has. So, testing
CustomerLoginServicelmpl becomes difficult
2.Also, you cannot use a different implementation of CustomerLoginReposttory other than
CustomerLoginRepositoryimp! because of tight coupling
So, a more flexible solution is needed where dependencies can be provided externally instead of the
dependent creating ts own dependencies, Now, let us see such an implementation
of CustomerLaginServicelmpl class0.7KB/s © & “ull
s.com/en/viev ©
2+ 4 Page 2 of? >
Consider the folowing modified implementation of CustomerLoginServicelmpl class
Poem
gee
vee sucie
Sere cast
omer
in this implementation, you can observe that CustomerServicelmpl does not create an object of
CustomerReposiory. Instead, CustomerServicelmpl is given an object of CustomerRepository when itis
instantiated through the eanstructor argument. You can pass the object of any elass that Implements
CustomerLoginRepository interface at the time of object creation of CustomerServicelmpl class as @
Constructor argument. This makes CustomerLoginServicelmpl class loosely coupled with
CustomerLaginRepositoryimpl class. So, you can naw also easily test CustomerServicelmpl class by
substituting its CustomerRepositorylmp! abject with a mack CustomerRepositary. Also, you can use any
Implementation of CustomerRepositor inside CusternerLoginServicelrnp
This solution is mote flexible and easy to test but at the same time, itis tedious to manually wire together
the dependencies. Also if you alter the dependencies, you may have to change huge amount of code.
Instead, a technique called Dependency Injection ()) is used. It's @ technique in which the responsibilty
of creating, assembling and wiring the dependencies of a dependent class is externalized to the external
framework or library called dependency injection (Ol) frameworks. Now the control over the construction,
wiring and assembly of an object no longer resides withthe dependent classes themselves, Ths reversal
of responsibilities is sometimes also known as Inversion of Control(loC). Dependency injection
framework are also called as loC containers,
‘There are many third party frameworks which are available for dependency injection such as Spring
Framework, Google Guice, Play Framework, ete. In this course, you will be learning about Spring
Framework Besides dependency injection, there are many other advantages of using Spring Framework
which you wil earn later in this course.Ra 11.7KB/s © @ ial @
ray @ lex.infosysapps.com
eee ie
ne
4 age 1 of 9 Spring Famenore
Spring Framework is an open source Java application development framework which supports building
all types of Java applications ike web applications, database driven applications, enterprise applications
and many more. Java applications developed using Spring are simple, easily
testable, eusable and maintainable, Some of the features are described below,
pet Seng Ik eres na
+ Absa omen wed ees tan 18
+ Con be epee Tomcat they er eae ery
eoteten are
‘Non inve + popiatansr deed un PONE
+ Noneed etendiplrent an ee define dsses
‘eos Coe
‘pg fete ne Dependency neon reps neta
| wen of Cone ac)
‘oc ator cestona objets that oe maraped bythe Sig Canine
sndther depeeneswerarhed atonal
‘sp Container
sep nets PoronningRa 41.1KB/s © @ “ull @
ray @ lex.infosysapps.com
ee eee tae
$M __> 4 Page_2 off» spingtvoton
Over the last decade, he Spring Framework has grown dramatically. So, tis worthy to have @ look at its
evolution. The following image depicts the important features that have come along with each release of
Spring, leading up to Spring Framework 5.0.
2017 | spring 5x 206+, runctenalrogranming eh Koin and Reactive oganming Model
2013 | spring 4xx 20K 6, conditions, websocats
2011 | spring 2.1 ava basad cantguaten, fas stubs suport Profee
2009 |— spring 2.0 Exton angge( Sel), Comprehensive FEST spyet ad suport for ES
Current version of Spring Framework is 5x. It has been enhanced with new features keeping core
concepts same as Spring 4.x. A high level, the new features of Spring Framework 5.x are
++ JDK baseline update
+ Core framework revision
“+ Reactive Programming Model : Introduces a new non-blocking web framework called Spring
WeoFlux
+ Functional programming using Kalin language support
«+ Testing provements by supporting integration with JUits
Let us look at Spring core relevant changes in deta:
DK baseline update
The entire Spring framework 5.x code base runs on Java 8 and designed to work with Java 9. Therefore,
Java Bis the minimum requirement to work on Spring Framework 5.x.
Core framework revision
‘The core Spring Framework 5.x has been revised, one of the main change is that Spring comes with its
‘own commons logging through springyel ar instead of standard Commons Logging,
“There are few more changes in Spring 5.x with respect to library support and discontinued supportca 11.1KB/s © @ ‘ull But G2
POM Maier Kool) ©
Pa eee aes
fp B_= 4 Pape _3 of + Spomg ode
Spring is organized in a modular fashion. The developer can pick and choose the modules as
per the need for building an enterprise application. Spring Framework 5.x has the following key
‘module groups:
* Spring Core Container: This module provides the Spring loC container and Dependency
Injection features,
* Spring Data Access/Integration: This module provide support to access database in Spring
applications.
+ Spring Web: This modules provide support to create web applications,
* Spring AOP: This module supports aspect oriented programming implementation
* Spring Messaging: This module provides support for integrating Spring applications with,
‘messaging systems.
=
Es
=e
naramatation eceaing
Now, let us see about Spring Core Container module in detail3:41 PM 1.5KB/s © @ “all Bat GD
POM Maier Kool) ©
Pa eee aes
£ R__+ 4 Page 4 off + Spring Core Container
‘The Spring Core Container has the following modules:
* Core: This is the key module of Spring Framework which provides fundamental support on.
which all other modules of the framework are dependent.
* Bean: This module provide basic Spring loC container called BeanFactory.
* Context: This module provides Spring 1oC container called ApplicationContext. which
extends the features of BeanFactory container and provides additional features for
enterprise application development.
+ Spring Expression Language (SpEL): This module is used for querying/manipulating abject.
value.ca SUE) CRON RM Pr erD)
ray @ lex.infosysapps.com
€ Ue introduction to Spring Frame Fle
© Onm
aver B
The development team needs to develop the data
access layer of Spring application to perform
database operations. Which of the following Spring
modules can be best used to achieve this
requirement? (Choose 2 options)
D web
D core
© on
ap
worn Pp
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)
> oe q
1D core container
Data Access modules -JOBC/ORM
D Testca SRL CIEROM eo
ray @ lex.infosysapps.com
ear
Spring framework provides a container for dependency injection. This container is called
2 Spring IoC container. it creates, intaizes and injects the required objects. These objects
whose life cycles are managed by Spring are called as Spring beans or beans. The Spring
container needs information about objects of which class to create and how to wire them
together. This information is called as configuration metadata. It can be provided in following
ways:
* XML configuration
* Java-based configuration
* Java Annotation-based configuration
‘Spring container reads the application classes using configuration metadata and then creates
{and wires beans in it as shown below:
pepcton dases
o
yeatin
ceatowaton Toc container
Objet conse
"he Apion
“Spin 6 Container
‘The Spring loC container is represented by the following interfaces:
* BeanFactory interface: It represents container which provides basic functionalities. It
instantiates bean whenever asked for by the client application. Using its getBean() method,
you can get instances of beans. It instantiates bean objects only when getBean() method is
called.
* ApplicationContext interface: It extends BeanFactory interface and provides additional
functionalities to support enterprise application development. It instantiates all beans when
container is loaded. There are many implementations of this interface. Some commonly
used implementation classes are as follows:
o ClassPathXmiApplicationContext : It is used to process XML-based configuration
metadata,
« AnnotationConfigApplicationContext : It Is used to process Java-based configuration
metadata.
"Now, let us see how to configure Spring IoC container and use itB= « Page _1_of3 contgvnglo container uing|nabased ontguaton metadata
‘The Java-based configuration metadata Is provided in Java class using following annotations:
* @Configuration The Java configuration class is. marked —_ with,
this annotation. This annotation identifies this as a configuration class, and it’s expected to
contain details on beans that are to be created in the Spring application context,
+ @Bean : This annotation is used to declare a bean, The methods of configuration class that
creates an instance of the desired bean are annotated with this annotation, These methods
are called by Spring container during bootstrap and the values returned by these methods
are treated as Spring beans. By default, only one bean instance Is created for a bean.
definition by the Spring Container, and that instance is used by the container for the whole
application lifetime,
For example, the CustomerLoginRepositoryimpl class can be configured in a Java class using
the above annotations as follows.
By default, the bean name is same as the name of method in which bean is configured. So, in
above code bean name is customerLoginRepository . If you want to change the bean name
then you can either rename the method or provide a different name with the name attribute as
follows:
rcs
The CustomerLoginRepositoryimpl bean has no dependencies of its own but
CustomerLoginServicelmpl class depends on CustomerRepository. So, you need to wire the
dependencies in configuration class. The simplest way to do this is to refer the referenced
bear's method as follows:
iogess
reer se mera cL aRTsU Testa ep)
een ogee Een oot
reeearst : rf 2__> 4 Pape _2_of9 + Contquonglo container ung Annotton sce contrat
So far, you have learnt that beans need to be configured in configuration class but in Java
annotation-based configuration, there is no need to explicitly configure the bean,
Spring automatically scans, detects and instantlates the beans from the specified package
through component scanning. It looks for classes annotated with following annotations:
+ @Component It is a general purpose annotation to mark a class as Spring bean
+ @Service - It is used to define a service layer Spring bean, It is specialization of
the @Component annotation for the service layer.
+ @Repository - It is used to define a persistence layer Spring bean, It is specialization of
the @Component annotation for the persistence layer.
reno
ecg sae
* @Controller - it is used to defined a web component. It is specialization of the
@Component annotation for the presentation layer.
By default, the bean name is same as class name with a lowercase initial character. Therefore,
the above defined beans have the names customerLoginController, customerLoginServicelmpl
‘and customerLoginRepositoryimpl. You can also glve specific name to a bean with a value
attribute of above annotations as follows:
‘The component scanning isnt enabled by default. You have to annotate configuration class
‘with @ComponentScan annotation to enable component scanning as follows:0.2KB/s © @ “ull
com/en/viev ©
Se
By default, the bean name Is same as class name with a lowercase initial character. Therefore,
the above defined beans have the names customerLoginController, customerLoginServicelmpl
‘and customerLoginRepositoryimpl. You can also give specific name to a bean with a value
attribute of above annotations as follows:
‘The component scanning isnt enabled by default. You have to annotate configuration class
with @ComponentScan annotation to enable component scanning as follows:
In the above code, Spring will scan the package that contains SpringConfig class and it sub-
packages for beans. But if you want to scan a different package or multiple packages then you
can specify this with the basePackages attribute as follows:
In above code, the Spring will scan com infy.service and cominfy.repository package and its
ssub-packages for beans.
If bean in your application are not having any dependencies, then component scanning
‘alone works but if beans have dependencies, then you have to inject dependencies in your
‘component-scanned beans, For this you have to do autowiring of dependencies. You will learn
this in the next module.
Discussion Forum,
Hac Benbarka Fo ag, nnn ano
Lavanya Pi hag sin ainan saeEye) 0.5KB/s © @
ray @ lex.infosysapps.com
fp B= 4 Page _3 09 + Unngloccontner
ApplicationContext can be loaded using AnnotationConfigApplicationContext class as follows:
‘The getBean() method is used to access a particular bean by specifying its class as follows:
‘The bean name which is the name of the method in which bean is configured can also be used
to access a particular bean as follows:ne
‘Objective:
To understand how to define configuration metadata using Java-based configuration and use
ApplicationContext.
steps:
Step 1: Create a new Maven project using Eclipse
‘Step 2: Add the following Spring dependency and properties in porn xm
een yey
Cee ree
Pe
oes
Puerco
eu
reac unin
‘Step 5: Create the followi
19 Userinterface class in com .infy.ul package with the main methodne
Step 4: Create the following configuration file in com.infy.configuration package:
eu
CeCe
Step 5: Create the following Userinterface class in com.infy.ui package with the main method
and instantiate the Spring container using configuration class you created in the previous step
as the constructor argument. Retrieve the WelcomeBean via getBean() method and use it.
nef] args)
oe to tal
Annotat:
Poe
Step 6: Run the Userinterface class created in the previous step. You will get the following
output
You can download this demo fromoe Oa en ee
ne
‘Objective:
To understand how to define configuration metadata using Java-Annotation based
configuration and use ApplicationContext
steps:
Step 1: Create a new Maven project using Eclipse
‘Step 2: Add the following Spring dependency in pom xm:
een yey
Cee ree
Pe
Pete coe
‘Step 5: Create the following Userinterface class
in com.infy.ui package with the main methodStep 5: Create the following Userinterface class In com.nfy.ui package with the main method
and instantiate the Spring container using configuration class you created in the previous step
as the constructor argument. Retrieve the WelcomeBean via getBean() method and use it.
Annotat:
Contex
ire:
Step 6; Run the Userinterface class created in the previous step. You will get the following
output
You can download this demo from bi
Discussion Forum,
WP <0eep>
V8) esponatotns ens
Start a new thread
Frag sup24an0sa700Rena 2.3KB/s ©
ray @ lex.infosysapps.com
Cee es
You know that Properties file can be read using Properties class but Spring
provides Environment class to directly access the values from properties file, The Environment
‘object can be abtained from ApplicationContext as follows:
Using Environment, property value can be fetched using getProperty() method as follows:
The location of properties file. Is mentioned in Spring configuration file
using @PropertySource annotation along with @Configuration annotation. For example,
‘messages properties which is present in classpath can be loaded using @PropertySource as
follows:
You can download a sample code of reading properties file from here.Rena 10.6KB/s ©
ray @ lex.infosysapps.com
Practices in java-Annotation based Configuration
‘Some of the best practices that should be followed in Jave-Annotation based configuration ar:
1. Use specialized stereotypes and NOT generic stereotype
‘As you have seen previously, @Component is a ‘generic’ stereotype for any Spring-managed
bean or component. We also derive @Service, @Repository and @Controller from
@Component, which are ‘specialized stereotypes used for classes implementing Service,
Persistence and Controller layers respectively.
@Component can be used interchangeably with any of the above derived specific stereotypes
and there will not be any significant issue or complication to the application. However, itis @
best practice to use the specific stereotypes for their respective layer implementations (which is
@Service for Service Layer, @Repository for Persistence Layer and @Controller for Controller
Layer).
2. Annotate ONLY classes and NOT interfaces
We should always annotate only the classes (and/or its methods) and not the interface which it
implements as Java does not allow the implementing classes to inherit the interfaces which are
annotated. Hence, itis a good practice to avold annotating the interfaces.ea ++034.5KB/s ©
ray @ lex.infosysapps.com
eee
ators Rp
Consider the following Spring bean and configuration
class:
package con.infy.cepository:
public class CustonerRepesttory<
>
package con.tnty. configuration:
configuration
public class Springcontigt
Bean
(astanerRepository custonerRepository(0¢
‘Custonertepository customer * new CustorerRapository 0)
>
What is the default name of
CustomerRepository bean ?
O cusom
O cusonaepotoy
O catomerepostory
© caszomertepestoy
cars Rp
Consider the following Spring bean and configuration
class:
package con.infy. service
public class Repistrationservicelapl (
public RepistrationserviceTep1() {
Systen.cut-println(-Repistration ln progress...)
,
>
package con.inty. configuration:
configuration
public class Springcontig ¢
‘ean
public Repistrationservicelapl registration() {
return new Registrationservicelmpl():,
,
>
Assuming that necessary imports are done, what is
the output when following code is executed?
chats con nt:
Public clare etter ¢
public stati vod mnn(Stringh arg) ¢
eplicationcotor ix = Rew Ata oot gh catonconext(Springontg. class:
,
>
O Restrain n progress.
(© Tre cose wi trowan exception trotine
(© Naming witbe aispaye cosecea 5KB/s © &
ray @ lex.infosysapps.com
eae
(© Te code wiinrow an exception tuine
O Noting witb pays cose,
aaofs RP
Consider the following Spring bean and configuration
class:
package con.inty. repository:
public class CastonerRepositoryin {
,
package con.inty. configuration:
configuration
public class Springcontig ¢
‘sean
public custonarRepositoryIupl custoeerRepositary()
return now CustorerRapasi tory gl)
,
>
Assuming that necessary imports are done, what is
the output when following code is executed?
package con.inty
public class Tester ¢
public statie veld main(String) args) ¢
‘doplicatlontontest ctx ~ new AimotationCofigpplicationContext(springContig.class)
{istonerRepositorytapl wt = cbs getdean(Custover Repository inpl-c1358)
(ustonerRepositorylmpl w2 = ctx getBeon(CostoerRepositorylnpl€1355)
Systen-out print
Systen-out-printn
wi ,equals(v2))
O mnetne
O mnie
O taerae
O tavetive
aor Rp
What is the default name of following
EmployeeRepositorylmpl bean ?
ecznponent
public class EnployecRepositorylnpl{
>
O exptyeetepestanymp!
© erpyetepstann
© tyes
O enployerepostorert
Q5ots pO ineine
O mnetaie
O taste
O faerie
aaots Pp
What is the default name of following
EmployeeRepositorylmpl bean ?
npn
PubIT class Enplysehpostoryepl{
,
O Erployeotepostorying!
O employetepostrying!
O Enployerpostorert
O enployerepostorert
sors Rp
Consider the following Spring bean and configuration
class:
schage con ty service
esrpuent (value = “pblisberservice")
public clase ubishersereestl ¢
>
schage con ty service
configuration
conparentscan(basrackages = “can. iny. service”
public class springeanigt
Which of the following are correct way(s) of getting
object of PublisherServicelmp! bean class? (Choose
any two options)
‘AppliationContext context = new AnnctatonConfigapplicatonContexspringonfig lass}
PublsherSericeimpl ps = context getBeanPublsnerserclmpl lass)
o
Aopleatencoren content= rew Annan nfenponcantestspngcont ast
PublsherServieimp) ps = context getBeanpublsherservi
o
Applicationcontext context = new AnnotatonConfigapplcaionContest(SpringConfig.class
PublsherSericeimgl ps = (Pubshersericelmpl} contest gtSean‘publisherservice";
a
Applicationcontext context = new AnnotatonConfigapplcaionContest(SpringConfig.class
PublsherServieimpl ps = (PubsherSericlmps} contest getBean PublsherSerice:
ocea 0.1KB/s © @ iat
ray @ lex.infosysapps.com
If one bean class is dependent on another bean class, then the bean dependencies need to be
explicitly defined in your configuration class but you can let the Spring oC container to inject
the dependencies into dependent bean classes without defining in your configuration
class. This is called as autowiring
To do autowiring, you can use @Autowired annotation, This annotation allows Spring loc
container to resolve and inject dependencies into your bean. It can be applied to attributes,
constructors, setter methods of a bean class.
Now, lel us see how to use @Autowired annotation,2 «Page 1 of3 » @hutoneson Proper
You can use @Autowired annotation directly on properties. For example, inthe following code,
CustomerLoginRepository is injected in CustomerLoginServicelmp! class using @Autowired
annotation
Cesta
Tage sue sa usec n ginName())
(rel gerst) TREE!
ose eer)
In above code, Spring container will perform dependency injection using the Java Reflection
‘API. It will search for the class which implements CustamerLoginRepository interface and
injects its object. The dependencies which are injected using @Autowired should be available to
‘Spring container when the dependent bean object is created. If the container does not find a
bean for autowiring, it will throw NoSuchBeanDefinitionException exception,
If more than one bean of the same type are available in the container, then the framework
throws an exception indicating that more than one bean is avallable for autowiring, To handle
this, @Qualifier annotation is used as follows:Page 1 of3 + aAutoneson Proper
eons
In above code, Spring container will perform dependency injection using the Java Reflection
‘API. It will search for the class which implements CustamerLoginRepository interface and
injects its object. The dependencies which are injected using @Autowired should be available to
‘Spring container when the dependent bean object is created. I the container does not find
bean for autowiring, it will throw NoSuchBeanDefinitionException exception,
If more than one bean of the same type are available in the container, then the framework
throws an exception indicating that more than one bean is avallable for autowiring, To handle
this, @Qualifier annotation is used as follows:
In the above code snippet, if Customerl oginRepository has multiple implementations then the
implementation which is registered in container with name jdbeRepository will be injected,
‘Autowiring is done only for dependencies to other beans. It doesnt work for properties such as
primitive data types, String, Enum, etc. For such properties, you can use the @Value annotation
(not covered as part of this course).
Now, let us see haw to use @Autowlred annotation on setter methods.2 T 4 Page _2 013 5 @hutoweden Sener metods
The @Autowired annotation can also be used on setter methods. This is called as Setter
Injection. For example, in the following code, CustomerLoginRepository is injected in
CustomerLoginServicelmpl class using @Autowired annotation on the setter method
ee ea et
ee su ere
ese
Cesta
eae
ct ee
In above code snippet, the Spring IoC container will call setter method for injecting the
dependency.
Now, let us see how to use @Autowired annotation on constructors.2 T 4 Page 3 of3 5 @hutonedon Constuctrs
The @Autowired annotation can also be used on constructor, This is called
‘as Constructor Injection. For example, in the following code, CustomerLoginRepository is
injected in CustomerLoginServiceimpl class using @Autowired annotation on constructor:
eer saciaat
Cae Stam ned
eget re
ng authentic
In the above code snippet, the Spring IoC container will call constructor for injecting the
dependency.eC) 0.0KB/s ©
(OMe Mane) cxeo)
a
objective:
To implement Customer Login user story using autowirin annotation based
fi
Step 1: Create a new Maven project using
Step 2: Add the f pring dependene in pom.xmi
ree eu
‘spring.
ones
eee
Cee sce st Cres)
ese
cere
Cee oe sUr eet 8)
resets
Pere
‘a package named
oo TC)
re
een
erg
eaten
een
Pemrsueurtg ccsu oes
eat ea ro ci)
Pare O net
Pree
Pee Peo
ec eee)eC) 0.1KB/s © PnP
(OMe MSA eSN ee) cxeou)
a
peers
Poe Poo ne
ec ee ee!
rots O net
eC Ces cs
and then create the following int
oO ese ia
Cea
fe
neu g era veya osc)
>
Step 5: Create the following class in cominfy. ory package:
OU ese ia
java.util
Sereatsee
Cee eur ee sr
ena
are
ven egereu yey su ce osm cuo ee
: Sec Ste
< 7 20
Erect see Tag
ree eee ses eae
Preece ascent Ise
recent use ea ge
Crees
O
retake s Oe ResCeCr su)
Ceca seer a Cec eet se Cmeame ee ttCLOD)
ree aerst)
oeC) 0.0KB/s © PP
(OMe MSA eSN ee) cxeou)
a
Step 6: Create a package named com infy.service and then create the fol
com. infy.service
OSC aC IC)
ene tec
ct
Pest eCLgG
rece tt)
,
Step 7: Create th ng class in com infy service package
Conese’
ae eee rt
ae eee eee ett
ee eee seen erst
Sees
infy.dto.
poste
sec ies
Cree sa coerac ae
authenticateCustomer(
Crees) Fi
rege sand
Pere Saag
Pecetec a Rrsu ersu) Ctra ersu eet ce)
geese cae Om Recs U ee Cees
i
Pca
toRet;
eerste
cca
Pooky aan aca EODyA) 0.0KB/s © PnP
(OMe MSA eSN ee) cxeou)
a
eee
Fe aan sca CEeTODY
Recc Ce Cec eT emote Tec
Becta
>
kage named com infy.controller and th
CoO ae rece
Cee Ua ee esc
See eae eer
Sener
eee ec
Cou mecastes
(
Crecr gesagt
authenticateCustomer(
Crean stp) {
rec ges Uc as tee aster eee Rat)
package named com.infy.configuration and create foll
init
CoO muse te Tstoy
ee eu ese std
ee eu eee ease Lasts
Pee eur ee Lest?
reece
rt
age properties file in src/main/resources folder:ERA 0.2KB/s ©
(OMe Mane) cxeo)
a
ing message properties file in src/main/
ame reed crt Cr cseses
Meese Str ame eee NTT
Step 11: Sj il configure logaj2 when the required dependency is added in pom.xml and
2 added in sre/main/t
ninfy.ul and create the following lass with
the main method init
com. infy.ui;
Cte cece ese
Cate eee aeeeeys
ee sue esd
Ce sO eee sc
Cee ue ee
Presets
Pen eease tt
oars
eee eC
cc a
)
PYG oe)
eee
Er Sete tetrentc nia
Po vete Tete ta
fe
environment=applicationContext.getEnvironment ()
er see aCe Deters eccots
eee ,
customerLogin =
regain RG Gg
ree gers eeeeecg
ree er soe eee strc erecta sep)
cos Cree ae TG Dy
pean rasta
etc eC ee nae ee coc LSC Eero DD)
+ment=
peer tal
POC
Pe Sees nvironment()
ges Cee Sree cots
ge See
toca UCI ae
, tar
eee chars
Note: InfyBankException class is already implented,
Step 13: Run the Userinterface class created in the previous step. You will get the following
output
+ For valid input, the output will be logged in console as:
* For invalid input, the output will be logged in console as
You can download this demo from hi
Discussion Forum,
TE) Thomas Latham Fa Fag pn sazata20m0
nnn the gt dependences sugested neve are unesteversons
VS esponsrotnsitvend12.1KB/s © @
ne
‘A best practice that should be followed while developing with Spring Framework is:
Use only managed beans and avoid directly instantiating a class
‘As you would have already noticed that we have not directly instantiated a class when itis used
‘as a managed bean as instantiating it directly using the new is considered to be a bad practice.
recy
stomer Login)
What could be the reason for this?
When a class Is used to instantiate a managed bean in Spring, it benefits from different features
of the framework. For example, each bean in Spring is a component and it can take advantage
of all services, Also, the bean is eligible for injection into other objects.
Hence, as a best practice, use only managed beans. Thus, the developers have to rely on.
Injecting the bean,
Eira strtcctriclaae
oc
sents
cs ‘ Tere aR st)
Pons
Whenever different instances of the same class is needed, Spring bean can be scoped as
prototype,te)
ators Rp
Consider the following Spring bean classes and
configuration class:
package con.snty. repository
public class Enployeckepositorylnpl{
Dublic String toString) ¢
return “Employeekopostoryigl"
,
>
package con.snfy. service
public class enplayecservicetapl ¢
‘hutonieed
private txployeetepesitorytapl employeatepsitory:
1 getter and setter nethads
>
package con. infy configuration
@contiguration
public class Springcontigh
eean
public ExployecRepositoryInpl enployetepository() 4
return new Erployeetoport trying)
,
>
Assuming all necessary imports are done, what
will be the output when following code is executed?
package con.infy:
public clare Userinterface (
public static void nain(Stringt] args) <
‘gplicationcontert context = new AmotationContighpplicationContext(Springcontig.clas);
{Exployeeservicelmpl enployeeService = (Exployeeservicelap context getBean“enployeeservicelrp
Sete avtprintinepopetervcegetepeteesitry0);
>
One
© NosuchBeandefinitonxception exception will be thrown,
O ervey!
(O NutPoirertacepton exception willbe thrown,
cars Rp
Consider the following Spring beans and
configuration class:
package con.tnty. repository:
public class ProductRepoestorylapl(
public Producthepositoryimpl(O¢
‘Systen.out.print("ProductRepesitorylnpl constructor called *)
,
>
package con. infy service
public class Productservicelapl{
‘tutonires
ProsuctRepositoryinpl productaepsitoryinpl;
public PraductServicetml(¢
‘Systenout print(“ProguctServicelapl constructor called “);
,
‘eT 0.0KB/s ©
ray @ lex.infosysapps.com
€ Lee _ Dependency injection using Autov
coors Rp
Consider the following Spring beans and
configuration class:
phage con ty egettor:
Bublie clare redctrooefcyingl¢
ible Produtos tryin
‘Syetensov pint Predetneponitorylml constructor called)
>
package con. infy service
public class Productservicetapl{
ProguctRepositoryinpl productaepsitoryinpl;
public PraductServicetml(¢
Systenout print(“ProguctServicelapl constructor called “);
,
>
package con. infy configuration
configuration
public class Springcontig «
‘ean
Public ProductRepositoryinl getProductepository() {
Teturn new ProductReporitoryinplQ)
»
public Productservicetml getproductservice() {
return new ProductservicelmplO;,
>
>
Assuming all necessary imports are done, what is the
output when following code is executed?
tage con int:
Public clare Terter {
pblic static void main(stringL) args) {
ApplicationGontent ctx = new AamotationcotiphplicationContext(SpringConfig.cl355)
© ProductRepositoryimpl constructor called ProductServicelmpl constructor called
rresxsancigcnsrcerce rotepstingontate cad
© neting ib esd on caste
(© fininesiepton ite tron,
eats Pp
Consider the following Spring bean and configuration
class:
package con.inty. repository:
Scanpanent(value ~ "eabineepesitory")
public elses Cabinkeposstoryt
public void display.)
Systen.out print("Inside Cabin Repository")
,
>
package con. infy service
lcenpanent(vslue = "csbinservice")
public elses Gbinservicet
iutorires
setetatt Miata iter cajillliessertliee.te)
ray @ lex.infosysapps.com
€ Lee _ Dependency injection using Autov
© Naming witbe sispaye on cosste
(© finanetxcepton ibe inom,
aaofs RP
Consider the following Spring bean and configuration
class:
package con.infy repository
lcenpanent (value = "
package con. infy service
feanpenent (value = "esbenservice")
public class Cabinservieet
utontred
private Cebinteporitory cabintepoitory
public vois display()(
‘systen.out printIn("Insige Cabin Service *);
‘abinkapository.diep19y0)
,
>
configuration
lecanponentsean(basePackages = "coninfy-repasitory")
public class springcontigt
,
Assuming all necessary imports and configurations
are done, what will be the output when following
code is executed?
pachage con int:
Dubie clare Userntertace
Public static veld main(String) args) {
dpplicaioncntextsplictlencetert~ nw AnottionantighplicatonconterSpringcotig. cat)
‘GbinService eablnservice = new Cabinservice()
cabinservice display);
(© Nosunaesnoesniontxeptanistronn
(© Inside cabin Service i preted ane en NosuerBeanDetirEscaptions thrown
(© Inside atin Sere nse Cain Repost
(© rns cain see preted and nen NulPoinerExeption town
sors p
package con.infy repository
Repository
public class Employeckepositorylnpl{
public Expleyeekepositorylnp]04
Systen.out prant("In Repository");
,
>
package con. infy service
public class Enplayecservicetapl ¢
ccsarenniedt3:48 PM ERC Pr exD)
POM Maier Kool) ©
€ Lee _ Dependency injection using Autov
(© Inside cabin Sere Inde Cabin Repost
(O ins cain sere preted and nen NulPoinerExeption town
ators p
package con.snfy. repository
Repository
public class Employeckepositorylnpl{
public Exployeekep plot
Systen.outprant("In Repository"):
,
>
package con. infy service
public class Enplayecservicetapl ¢
‘hutonieed
Drivate Exployestepesitoryiael enployeetepositry;
package con. infy. controller)
controller
public class Employeecontrolterd
‘Wutorires
Drivate ExployeeServicelnpl enployeeService:
public exployeecontroller()¢
Spsten-out.print("In ControLler *);
,
>
package con. infy. configuration
configuration
lcenponentScan(basePackoge
public elses Springtontiet
,
con. infy-repository con.infy. service con. infy. controler")
Assuming all necessary imports and configurations
are done, what will be the output when following
code is executed?
sachage con nt:
Public class userntertace ¢
Public static wold malmstringt) args) ¢
dpolicaioncntertsplicsloncartert = ne Anattionantggplieatonconter(Springcotig. cat)
taploystonrelier eaployestonrelir = appicaioncontergetean(eaployestotreier ass)
,
>
(O tnrepestory sericea Cooter
© tncontronern Service a Repository
(© tnrepestor cartes printed and then NesueBeaetatientxception stow
(© tntepestory seven Conor priced an then NasudBesnDeasonExcepon tvoun
ots p
Consider the following Spring bean classes and
configuration class:
package con.infy repository
public class Enployeckepositorylnpl{
public String toString) ¢
return “Employeekopository ipl"te)
Pee ne
Backage con inf
public clare Userinterface (
public static void nain(Stringt) args) «
‘oplicatsoncontert appLicationcontext = new AnotationConfiptpplicatoncontex( Springconfig. lass)
EnployeeController enployeeCotroller = applicationcentextgetBean Enployeeontroller€1355)
,
>
‘© In Repository n Serie in Controier
© In consroier in Service n Repository
tnt incoaeri pit ante sitet
(© tntepestory service n Conor priced anthen NasuBesnDeatonExcepon tvoun
sors Pp
Consider the following Spring bean classes and
configuration class:
package con.Snty repository
public class Enployeckepositorylnpl{
public String toString) ¢
return “Employeekopository ipl"
,
>
package con. infy service
public class EnplayeeServicelmpl ¢
‘utonired
private Enployeokepositorylnpl enployceRepsitory
17 getter and setter methods
>
package con.inty. configuration:
configuration
public class Springtontigi
‘ean
Public Employeckopositorylnpl enployeaepsitory()
return new EmployeeRepositoryimp10;
,
00
public EmployecServicelupl enployeeervicelnpl() (
return new EnployeeServicelMpl0:
,
>
Assuming all necessary imports and configurations
are done, but code will not be executed due to Line 1,
Correct the Line 1 of Application(Choose 3 options)
package con int
public class Useranterface ¢
public Static void nain(stringt) args) «
‘Agplicationcontext context ~ non RaetatooContigipplicationContext(Springcontig-clas):
Expleyeeservicelapl enployecService = catext.getbean(veqployeeServicelapl*): //Linel
Systen-out-prantin(empoyeeservice, geteployeetepes!t0ry())
,
>
Emplayeeserscelmpl employeeservice = context getBeanemployeeserviclmpl lass":
Employeeservcemplemployeeservice = mployeesericelmpl) contest getBeanemployeeSericelmp
Employeeservcelmpl employeeService = context getBean(EmployeeSerdcelmpllass
oooa
Employeeservcelmpl employeeService = mployeesericelmpl} contest getBeanfEmployeeserdcelmpl.lass):Een 0.0KB/s © & “ull Bat GED
POM Maier Kool) ©
Dependency Injection using Autowiri
Problem Staternent
‘An insurance company provides different type of life insurance policies. it needs an application
with following functionalities:
1. Buy an insurance policy
2, Generate report based on type of policy
‘This application is partially implemented. You have to implement service layer of this
application, Follow the following instructions before starting coding:
1. Click here to download the project
2. Import the downloaded project in your workspace.
3. Implement the validator and service class according to given description.
‘The description of different classes is given below:
11. Model classes (already implemented)
+ PolicyReportDTO
+ PolicyDTO
2. SpringContig class (to be implemented)
This Is the configuration class of application. Implement this class according to class dlagram
and description given below:tT 0.2KB/s ©
ray @ lex.infosysapps.com
Dependency Injection using Autowiri
+ Annotate it proper annotation to declare it as Spring configuration class,
‘Method description:
+ insuranceServiceQ)
© This method configures the InsuranceServiceimpl bean,
© Annotate it with proper annotation to specify that it returns a bean to be managed by
‘Spring container.
o It should create and return an object of InsuranceServicelmpl class.
+ insuranceRepository()
© This method configures the InsuranceRepositoryimpl bean,
© Annotate it with proper annotation to specify that it returns a bean to be managed by
‘Spring container.
o It should create and return an object of InsuranceRepositoryimpl class,
3. Validator class (to be implemented)
This class is used for validating the input values. Implement this class according to class
diagram and description given below:
Note: All the methods of this class are static.
Method description
* validate(PolicyDTO policy)
‘This method validates the policy details by Invoking respective validator methods. If validation
falls, throw insurance€xception with the corresponding messages as shown in the table below.
polleyhunber | Vator NVALID POLY NUMBER
= | ee
[poloyoldernone | ltr IAL, HODER MOE
| exwormieen | veidtecnvatm_000
polteynane tec VAL POLICY MAME
SS
[puto vntecvaun POLITE
preniun Vottovat_ pneu
t
“ceuretaonths | Vator tNVALD_TENURE
* validatePolicyName(String policyName)
© Themed salitame polarne,Ra 0.1KB/s © @
POM Maier Kool) ©
Ma cua.
+ validatePolicyName(String policyName)
» The method validates policyName.
© The policyName should contain only alphabets and it should not be emply.
© Ifthe above conditions are satisfied, return true, otherwise return false.
+ validatePolicyType(String policyType)
® This method validates policyType.
« The policyType should be one among following:
* Term Life Insurance
= Whole Life Policy
+= Endowment Plans
® If the above conditions are satisfied, return true, otherwise return false. Perform case
‘sensitive operation,
* validatePremium(Double premium)
o This method validates premium:
© The premium should be more than 100,
© If the above conditions are satisfied, return true, otherwise return false.
> + validateTenure(integer tenurelnMonths) q
© This method validates tenureinMonths.
+ The tenureinMonths should be more than 24
« Ifthe above conltions are satisfied return true, otherwise return false
+ validateDateOfBirth(LocalDate dateOfBirth)
© This method validates dateOfBirth.
© The dateOfBirth should be before today.
« Ifthe above conltions are satisfied return true, otherwise return false
+ validatePolicyNumber(String policyNumbersString policyType)
« This method validates polieyNumber.
© The policyNumber should be in <<1st Part>>-<<2nd part>> format.
© 2nd partis a 6 digit number
© Ist part is as per the table below:Ra 0.0KB/s © &
POM Maier Kool) ©
Ma cua.
+ If the above conditions are satisfied, retum true, otherwise return false. Perform case
sensitive operation,
+ validatePolicyHolderName(String policyHolderName)
© This method validates policyHolderName
© The polioyHolderName should contain atleast 1 word of length atleast 3.
© If there are more than 1 word then each word should be separated by single space and
should not be empty.
© If the above conditions are satisfied, return true, otherwise return false,
4, InsuranceServicelmpl class
This is the service class of application. Implement this class according to class diagram and
description given below:
instance varlable description
* Inject insuranceRepository using autowiring
Method description
> * buyPolicy(PolicyDTO policy) q
© This method invokes validate of Validator class to validate the policy details
© Ifall the detalls are valid, it invokes buyPolley() of InsurancRepositoryimpl class, which
intum returns a string,
» Itretums the string received in previous step,
» Itlogs Insurance€xception thrown from service and validator class and re-throw them,
+ calculateAge(LocalDate dateOfBirth)
© This method calculates and return the age of policy holder from current date in terms
of months.
+ getReport(String policyType)
© This method returns a lst of all the policies of specified policyType.
® It invokes the getAllPolicyDetails() of InsurancRepositorylmpl class which returns a
ListePolieyDTO>,
® Filter the list obtained in previous object to get those policy whose type is equal to the
policyType received by this method.
© Create and populate a new List using the filtered list obtained in
previous step. For each PolicyReportDTO object, set the value of policyHolderAge using
the calculateAge method of InsuranceService,
olf the filtered list is empty, throw an InsuranceException with message
“Service. NO_RECORD’, else return the ListPolicyReportDTO> obtained in previoustT 0.0KB/s © @
ray @ lex.infosysapps.com
Ma cua.
yareiconanennr ysis wisuemnncen ret
olf the filtered list is empty, throw an Insurancetxception with message
"Service.NO_RECORD’, else return the List obtained in previous
step.
» Itlogs Insurance€xception thrown from service and validator class and re-throw them.
5. InsuranceRepositoryimp| class (already implemented)
This is the Repository class of this application and itis already implemented.
+ buyPolicy(PolicyDT0 policy)
Method description
© This method is used to save the policy details in database.
+ getallPolicyDetails)
© The method return details of all the policies,
6. Userinterface class (already implemented)
Userinterface class is used as an interface between the application and the user. The methods
Of this class are already implemented,
‘You can modify the inputs to check output for various scenarios, Some valid and invalid input
values and expected output is given below:
buyPolicy)
+ For following valid values for Policy
oleymber | WLSSIOI2
oceans | James
a
soles | wilt ae
‘The output should be logged in console as: The policy successfully added with policy number:
WL-553912
* For invalid policyName name/Retirement Plan’ , output should be logged in console as
Policy name is invalid.
+ For invalid policyType, "Org-infy-044", output should be logged in console as : Polley type is.
Invalidel) 0.0KB/s ©
ray @ lex.infosysapps.com
ee ee
You can moanly ine npu's (O Check OUIpUL 1Or various sceNaNos, Some vanla ana invana NpUL
values and expected output is given below:
buyPolicy)
* For following valid values for Policy
‘The output should be logged in console as: The policy successfully added with policy number:
WL-553912
* For invalid policyName name/Retirement Plan’ , output should be logged in console as
Policy name is invalid.
+ For invalid policyType, "Org-infy-044", output should be logged In console as : Policy type is
invalid
+ For invalid premium "123.0", output should be logged in console as: Premium is invalid
* For invalid tenure, "12°, output should be logged in console as: Tenure is invalid
* For invalid dateOfBirth, "22-Jan-2022", output should be logged in console as: Date of birth
Is invalid
+ For invalid policyNumber, “TL-12345676", output should be logged in console as: |
‘number is invalid
* For invalid policyHolderName, ‘J@mes’, output should be logged in console as: Policy
holder name is invalid.
generateReport()
* For valid policyType: "Term Life Insurance’, output should be logged in console as:
PolicyReportOTO [policyNumber=T1-309981, policyHolderName=Maria,
policyHolderAge=374 0, tenureinMonths=300)
PolicyReportOTO IpolicyNumber=11-852189, policyHolderName=Roger,
policyHolderAge=536 0, tenureinMonths=100)
hn M,
PolicyReportDTO —_—_[policyNumber=TL-002319, _policyHolderNam.
polioyHolderAge=152.0, enureinMonths=420]
* For invalid policyType: “CEO 8, output should be logged in console as: No record exist for
this policy type.
Discussion Forum,ETT 0.3KB/s © &
ray @ lex.infosysapps.com
ed cunt
Problem Staternent
InfyDASystem needs an application for allocating desktop to the trainees with following
modules:
1. Add new trainee
2, Get desktop allocation details of each trainee
‘This application is partially implemented. You have to implement service layer of this
application, Follow the following instructions before starting coding:
1. Click here to download the project
2. Import the downloaded project in your workspace.
3. Implement the validator class and service class according to given description.
‘The description of different classes is given below:
11. Model classes (already implemented)
+ TraineeDTO
* DesktopDTO
2. SpringContfig class (to be implemented)
This is the configuration class of application. Annotate it proper annotations do declare it as,
Spring configuration class and auto scanning of beans present in cominfy.service and
cominfy.repository package.
3. Validator class (to be implemented)
This class is used for validating the input values. Implement this class according to class
diagram and description given below:
Note: The methods of this class are static.ya 0.0KB/s ©
ray @ lex.infosysapps.com
Dependency Injection using Autowiri
Note: The methods of this class are stati.
‘Method description
+ validate(TraineeDTO trainee)
© This method validates the trainee details by invoking respective validator methods. If
validation fails, throw InfyDASystemException with message as shown in the table
below:
trinsld | Voto NVALIO_DETALS
* validateTraineePhoneNo(String phoneNo)
© This method validates the received phoneNo.
© The length of the phoneNo should be 10 digits.
© The first number in the contactNo should be either 7,8 or 9
® If the above conditions satisfy, return true else return false,
4. InfyDASystemServicelmp! (to be implemented)
‘This is the service class of application. Implement this class according to class diagram and
escription given below:
+ Annotate it with proper stereotype annotation with value infyDASystemService’
+ Inject the infyDASystemRepository using autowiring
Method description
+ addNewTrainee(TraineeDTO trainee)
© It invokes validate) of Validator class to validate the trainee details,
off all the details are valid, invoke adcNewTrainee) of InfyDASystemRepositoryimp,
which in turn returns an integer.
® Itreturns the integer recelved in previous step.
» It logs InfyDASystemException thrown from service and validator class and rethrow
them,
* getAllocationDetails(Integer traineeld)
» This method returns the desktop allocation details for the given traineeld,
® It invokes the getAllocationDetails() method of InfyDASystemRepositoryimp! which
returns the trainee details,
© If trainee details are not found it throws an InfyDASystemException with message
"Service.NO_DETAILS_ FOUND’, else returns the trainee details found in previous step.
Teg NRIDASHSleenti then hom sere ees and eae tien.3:52 PM 0.0KB/s ©
ray @ lex.infosysapps.com
Dependency Injection using Autowiri
© Itlogs InfyDASystemException thrown from service class and re-throw them.
5. InfyDASystemRepositoryimpl (partially implemented)
‘This Is the Repository class of this application and its methods are already implemented, You
have to annotate it with proper stereotype annotation with value “infyDASystemRepository’
+ addNewTrainee(TraineeDTO trainee)
Method description
This method is used to save the trainee details in database.
+ getAllocationDetails(Integer traineeld)
© This method returns desktop allocation detalls ofa trainee,
6. Userinterface class (already implemented)
Userinterface class is used as an interface between the application and the user. The methods
Of this class are already implemented,
addNewTraineeQ)
+ For valid trainee details:
—om 08
rae —_[ Robin
|phoneno—_|s4ns55061
* The output should be logged in console as: Trainee added successfully with id: 1008
+ For invalid trainee details
GSES
0 8
ne bin
Phone SSSIBL
‘The output should be logged in console as Invalid trainee details
getAllocationDetails()
+ For valid traineeld-1001, output should be logged in console as.
TraineeDTO [id=1001, _name=Adam, —_phoneNo=9658014355, _ desktop=DesktopDTO
machineName=MYSGECTI1111D, make=Acet]
a Ror ieweldd traneead 1002. nuteorehauid-be joed in conealese he wernes ante Torte3:52 PM 0.0KB/s © &
ray @ lex.infosysapps.com
ee ee
+ addNewTrainee(TraineeDTO trainee)
© This method is used to save the trainee details in database.
+ getAllocationDetalls(integer traineeld)
« This method retums desktop allocation details of a trainee.
6. Userinterface class (already implemented)
Userinterface class is used as an interface between the application and the user. The methods
Of this class are already implemented,
You can modify the inputs to check output for various scenarios, Some valid and invalid input
values and expected output is given below:
addNewTrainee()
+ For valid trainee detalls:
je
ie [tn
[pioneer
+ The output should be logged in console as: Trainee added successfully with id: 1008
> * For invalid trainee details q
me ebin
Phono SSSI
‘The output should be logged in console as ‘Invalid trainee details
getAllocationDetails()
+ For valid traineeld 1001, output should be logged in console as:
TraineeDTO —[id=1001, _name=Adam, —_phoneNo=9658014355, desktop=DesktopDTO
ImachineName=MYSGECT11111D, make=Acet]
+ For invalid traineeld = 1002, output should be logged in console as: No trainee exists for the
specified id
Discussion Forum,
‘There arent any conversations yet
Start a new thread
—3:52 PM 0.0KB/s © &
ray @ lex.infosysapps.com
ea
fp B__= « page _1 of6 » neeatorsprngoct
You have learnt that Spring is @ lightweight framework for developing enterprise Java
applications but using Spring for application development is challenging for developer because
of the following reasons which reduces the productivity and increases the development time:
1. Configuration
You have seen that Spring application requires lot of configuration. This configuration
also needs to be overridden for different environments like production, development, testing,
elc. For example, the database used by testing team may be different from the one used by
development team. So, we have to spend lot of lime in writing configuration Instead of writing
application logic for solving the business problems.
2. Project Dependency Management
When you develop a Spring application, you have to search for all compatible dependencies for
the Spring version that you are using and then manually configure them. if wrong
version of dependencies is selected, then it wll be an uphill task to solve this problem, Also, for
every new feature added to the application, the appropriate dependency needs to be identified
and added,
All these reduce the productivity
It would be much more better if the productivity could be Improved by using a better
framework,
Such a framework is Spring Boot.ya 4.4KB/s © Bn Baal GD
POM Maier Kool) ©
eee
+ 4 rage 2 of + atsspingtoor
Spring Boot is a framework built on the top Spring framework that helps developers bulld
‘Spring-based applications quickly and easily. The main goal of Spring Boot is to quickly create
Spring-based applications without requiring developers to write the same boilerplate
configuration again and again.
How does it work?
It works because of following reasons:
1. Spring Boot is opinionated framework
Spring Boot forms opinions. It means that Spring Boot has some sensible defaults which you
can use to quickly build your application. For example, Spring Boot uses embedded Tomcat as
the default web container.
2. Spring Boot is customizable
Though Spring Boot has its defaults, you can easily customize it at any time during your
development based on your need. For example, if you prefer log4j for lagging over Spring Boot
builtin logging support, then you can easily make dependency change in your pom.xml file 10
replace the defauit logger with log4j dependencies.
‘The main features of Spring Boot are as follows:
+ Starter Dependencies
+ Automatic Configuration
+ Spring Boot Actuator
> + Embedded Servlet Container qRa 0.5KB/s © & “al @
ray @ lex.infosysapps.com
4 Page _3 016 + Spring Boot starters
Spring Boot comes with many starters. Spring Boot starters are pre-configured dependency
descriptors with most commonly used libraries that you can add in your application, So, you
dont need to search for compatible libraries and configure them manually. Spring Boot will
ensure that the necessary libraries are added to the build. To use these starters, you have to
{add them in the pom.xml file. For example, to use spring-boot-starter, following dependency
needs to be added in pom.xml
‘Some popular starters which we are going to use in this course are as follows:
+ spring-boot-starter - This is the core starter which includes support for auto-configuration,
logging and YAML.
* spring-boot-starter-aop - This starter is used for aspect-oriented programming with Spring
‘AOP and AspectJ.
+ spring-boot-starter-data-jdbe - This starter is used for Spring Data JDBC.
+ spring-boot-starter-data-jpa - This starter is used for Spring Data JPA with Hibernate,
* spring-boot-starter-web - This starter is used for building web application using Spring
MVC and Spring REST. It also provides Tomeat as the default embedded container.
+ sping oot startertest- Ths starter proves support er testing Ser Steppers]
* spring-boot-starter-iog4j2 - This starter provides support for using Log4j2 for logging. It is
an alternative to spring-boot-starter-logging
+ spring-boot-starter actuator - This starter provides support for using Spring Boot Actuator.Eee)
0.4KB/s © @ “at Bal GD
POM Maier Kool) ©
eee
R= rape 4 16 + spemgteatanocomeraton
Spring Boot uses auto-configuration to automatically configure application by providing the
basic configuration required to run the application based on the jar dependencies available on
the classpath, Ths eliminates the need of manually configuring Spring applications.
For exampk
If you are using JDBC in your Spring Boot application, then there is no need to
configure any database connection beans. AS soon as Spring Boot detects that you have
DBC library in application's classpath, it will automatically configure database connection
beans.
You wil earn more about the auto configuration as you proceed in this course.3:53 PM 0.4KB/s © @ ial
ray @ lex.infosysapps.com
Spring Boot Starter arent
‘The Spring Boot Starter Parent defines key versions of dependencies and default plugins for
uickly building Spring Boot applications. It is present in pom.xml file of application as a
parent as follows:
Og a
eet :
os
Itallows you to manage the following things for multiple child projects and modules:
+ Configuration ~ The Java version and other properties
* Dependencies ~ The version of dependencies
+ Default Plugins Configuration ~ This includes default configuration for Maven plugins such
‘as maver-failsafe-plugin, maven-jar-plugin, maven-surefire-plugin, maven-war-plugincea 0.4KB/s © @B ial Baal GED
POM Maier Kool) ©
eee
fF B= 4 Pape _6 6 + Approachstor renting Seng oot ppstion
There are multiple approaches for creating Spring Boot application. You can use any of the
following approaches:
+ Using Spring Initaizr
+ Using the Spring Tool Suite (STS)
+ Using Spring Boot CL!
+ Using Spring Maven Project
In this course, you will learn how to use Spring Initialize for creating Spring Boot applications.2
‘Objective:
To understand how to create a spring Boot application
steps:
Step 1: Launch Spring Initializr to create your Spring Boot application. You will get following
screen:
Note : This screen might change depending on updates from Pivotal and change in Spring Boot
version.
Step 2: Select Project as Maven Project, Language as Java, and Spring Boot as 2.9.1 and enter
the project details as follows:
* Choose com infy as Group
+ Choose Demo_SpringBoot as Artifact
+ Choose Demo_SpringBoot as Name
* Choose Demo project for Spring Boot as Description
* Choose com infy as Package name
*» Choose Jar as Packaging
* Choose 11 as Java version
You will get following screen:Een CALGON et]
ray @ lex.infosysapps.com
ae
= Unvuse vat as raLKayiiy
ee cee ae ged
* Choose 11 as Java version
You will get following screen:
Step 3: Click on Generate Project. This would download a zip file to your local machine.
‘Step 4: Unzip the zip file and extract to a folder,
Step 5: In Eclipse, click File + Import -- Existing Maven Project. Navigate or type in the path of
the folder where you extracted the zip file to in the next screen. AVter finishing, our Spring Boot
project should look like as follows:
Bh oom spin
> 3 i bensptaniepiienie q
> Gf bonspnsaatoattaso
Brent
Some
Bam
Step 6: Execute the Spring Boot application by running the DemoSpringBootApplication as a
standalone Java class. This class contains the main() method. On successful execution you will
¢get following output in console:
You can download this demo from here.
Discussion Forum,
There arent any conversations yeteT) 30.4KB/s ©
ray @ lex.infosysapps.com
Pan Oe eee a cet
ct generated in the previous wing files:
1. pom.xml
This file contains information abo #t and configuration
bulld the project.
Sees Cosas
4.0.0
re ete eg
pene at es
Preis
Een
Cooma,
Pee rsuccs
CSG
Peeters
Peas!
ee eu Cas
Sate rted
starter
Ce euros
eg er eete ec
Cee reais
crs
vintage-enginens
Pee eeo Cee
eters
PU eae TaaC]
Pe
trues
2. application properties
\This file contains application-wide properties, Spring reads the properties defined in this file to
‘configure your application, You can define a server's default port, servers context path,
database URLs, elc. in this fle
3, DemoSpringBootApplication java,
‘This class is by default generated by Spring Boot to bootstrap Spring application:
It is annotated with @SpringBootApplication annotation which triggers auto-configuration and
‘component scanning and can be used to declare one or more @Bean methods also. It contains
the main method which bootstraps the application by calling the run{) method
(on SpringApplication class. The run() method accepts DemoSpringBootApplication.class as
parameter to tell Spring Boot that this is the primary component.1.1KB/s © “i
2. application properties
‘This file contains application-wide properties. Spring reads the properties defined in this file to
configure your application. You can define a server's default port, servers context path,
database URLs, etc. in this file.
3, DemnoSpringBootApplication java,
‘This class is by default generated by Spring Boot to bootstrap Spring application:
rae
It is annotated with @SpringBootApplication annotation which triggers auto-configuration and
‘component scanning and can be used to declare one or more @Bean methods also. It contains
the main method which bootstraps the application by calling the run method
(on SpringApplication class. The run() method accepts DemoSpringBootApplication.class as
parameter to tell Spring Boot that this is the primary component.
4, DemoSpringBootApplicationTests.java
In tis file, est cases are written.
Discussion Forum,
$5) sehabharathis Fa Fag cr ngan tana
PN) PraveenkumarNR Farag. oxizz ant ceo
balsa contains papas32.7KB/s © “i
2+ Understaning
We have already seen that the class which is used to bootstrap Spring Boot application is
annotated with @SpringBootApplication annotation as follows:
Now, let us understand this annotation in detail
‘The @SpringootApplication annotation indicates that it Is a configuration class and also
‘riggers auto-configuration and component scanning, It is @ combination of the following
annotations with their default attributes:
+ @EnableAutoConfiguration - This annotation enables auto-configuratlon for Spring Boot
application which automatically configures your application based on the dependencies
thal you have added
= @ComponentScan - This enables Spring bean dependency injection feature by
using @Autowired annotation. All application components which are annotated
with @Component, @Service, @Repository or @Controller are automatically registered as
‘Spring Beans. These beans can be injected by using @Autowired annotation,
+ @Configuration ~ This enables Java based configurations for Spring boot application.ne
‘So far, you have learnt how to create and start Spring Boot application. If you want to perform
‘some action immediately after the application has started, then for this Spring Boot provides
following two interfaces:
* CommandLineRunner
* ApplicationRunner
‘CommandLineRunner is a Spring Boot interface with a run method. Spring Boot automatically
calls this method of all beans implementing this interface after the application context has been
loaded,
To use this interface, you can modify the DemoSpringBootApplication class created in the
previous demo as follows:
oot
Pe
Pees
Cree eurie
eeu
After executing, you will get the following output:
é nam Coe * xe) RODBEl=0-n-Rt) E Bul GD
Spring Boot application is configured using a file named application properties. It is auto
detected without any Spring based configuration and is placed inside “src/main/resources*
directory as shown below
Bh oma spngtet
ib manne
Sane,
al
sek
‘cmt
2 i donspmstonipinentesne
9 m itp
3 re emcee
3B
Seve
B tetrme
i=
Seon
Bem
In this file, various default properties are specified to support logging, aspect-oriented
programming, etc. All the default properties need not be specified in all the cases. We can
specify them only on-demand. At startup, Spring application loads all the properties and adds
them to the Spring Environment class. To use a custom property, the property needs to be
‘added to the application. properties file. Then, the Environment class should be autowired into a
class where the property is required and the property should be read from Environment
using getProperty() method.ne
‘Objective:
To understand how to implement Customer Login user story using Spring Boot,
steps:
Step 1: Create a new Spring Boot project using Spring Intializr with following project structure:
dbo Son coe
Comrie
2D cometag terete
~@tonntuoen
I comrctnecancnon
omy
Step 2: Create the following class in cominfy.dto package:
Seat
See sce
poste
Pacers)
co
aes
Step 3: Create the following interface in com infy.repository package:Rt) 20.6KB/s © @ “0 ed}
(OMe MSA eSN ee) cxeou)
€ lef spring Boct- Demo
ninfyrepository package:
ORT TsReIay
Cea
rt
nena g ervey sue esc)
tory package:
cerry
eee en ees
ener
t
Peneeceaereu ere eye oncom
< i Sareea
< 7 >O
Crete ase Sea Tag
Pree eee ses ease
reece uses en Ise
recent See ae
Cree so
)
Pec CRC Ra tec noe
ge see a Cee Se eee UD
reece eeety
ng interface in com infy service package
Come
com. infy.dto
i
Siete ect ing
ustomerLogin)
rsRt) 0.0KB/s © ® ed}
(OMe MSA eSN ee) cxeou)
€ lef spring Boct- Demo
Coon meCa ccs
Ce
rt
eMrstet erring
recast) A
,
Step 6: Create th ng class in com.infy service package
Conese’
ee Une eee oC
Cee eae eee!
oC aCts
eee ee Cr
com. infy.reposito
Creer ee sacs
Brest
customer Login) ra
oa
eee eee ee tcinne
reer suc rceag
Potent ey su ecg Ryu atest LOD)
(rec g esi meee Oe tect aks esta
4
Poa
roca
ntroller cl ontroller package a:Rta 0.7KB/s ©
(OMe MSA eSN ee) cxeou)
€ lef spring Boct- Demo
Step 7: Create the following CustomerLoginc:
follows:
cee
eee eure oe eo
Cree eu ie ees oe
cue c)
ener tec
en aes
eee
Cree tnccaaty
Eira ete tect ing
rercr amet) 4
b=
ree asta este eet)
a= Add the flowing properties o application properties file
meats Teed coo Cece ses
SUCCESS=! ce Mme eO TET
diy the DemoSprin reAppli
oot
org.apache.conmons.. logging.
ee eee eet ‘
ee ean ee oer eet
eee eure era es
ee eae era es
ee eur ee Coe ces
Se eu eee
couse sect
Sener
Out styne
eee
eee ECR
rsur crt
cae
cae
Senne Cette ete aera)
CSUs Caer ees a »)
} tp cueter eco SSC
Note: InfyBankException class is already implented,
Step 10 : Run the DemoSpringBootCoreApplication class created in the previous step. You will
get the following output:
+ For valid input
+ For invalid input
You can download this demo frometa OKB/s © @
ray @ lex.infosysapps.com
© © ines
ovat Pp
Assuming that necessary imports are done, what is
the output when following code is executed?
package con.infy. service
service
Dublic class GastonerService ¢
Dublic Gustonerservice()(
'Systen-outprint("CustomerService constructor called “);
,
>
package con.inty. repository:
BRepositery
public class CustonerRepesitory ¢
public CustonerRepositary() ¢
Systen.cut.print("CustowerRepository constructor called ");
>
>
Backage con.inty
springboovipplication
public class DewospringBootépplication ¢
pblic static void main(String) 23s) (
Springlpplleation.run(Deraspringbootapplicationlass, args):
(© ciutomerserie constrictor cle CustmerRepostar constr ales
(© caszomertepostory constructor ale Cusomerserie costco aed
O Noting ibe cays in consce
wots Rp
What is the name of configuration file of Spring Boot
application?
© coonuaton ropes
© septeaton ropes,
O ceongpropeies
© eenpropertis
wots Pp
Which of the following starter you will add in
pom.xml file of Spring Boot application
for using Spring MVC?
© spring booeweb starter
O spring dooestarec
© seine eermestrer
O sping boestarer me© castomertepostry onstuco caea Cusamarserdceconstce ales
© Naming witb sispaye in cose
ots Pp
What is the name of configuration file of Spring Boot
application?
© contusion properties
O application properties
© ceotipropertes
© vvnprnenes
coors Rp
Which of the following starter you will add in
pom.xml file of Spring Boot application
for using Spring MVC?
O spring booted starter
O spingboorsrci
O str boot ester
© sping beastaterme
ots p
The @SpringBootApplication is combination of which
of the following annotations? (Choose 3 correct
options)
D @ Configuration
1 e@tnabiesstoconfigurtion
D @componentsean
D @component
esots p
Match the following
Ercan as Tareq era
tue ropes
‘abs 008 nee
aa eer Taiored he one
Tre Fraropet arte pope)
otaspingsppeen34.7KB/s © Be ull Bal GSD
Problem Statement
‘ABC Solutions provides online business consulting and outsourcing services. They want to
automate the project allocation process, The application has following two modules:
1. Add new projects
2. Generate report of each project
You have to develop the service layer of this application. Follow the following instructions
before starting coding:
1. Click here to download the project.
2. Import the downloaded project in your workspace.
3. This project Is partially implemented. You have to implement the DTO classes, validator
class and service class.
‘The description of different classes is given as follows:
1. DTO Classes
+ ProjectDTO (already implemented)
» The following Is the class diagram for this class:
+ TeamMemberDTO (already implemented)
» The following is the class diagram for this class:
2. Validator class (to be implemented)
This class is used for validating the input values. Implement it using class diagram and
description given below:[PT Pre
Note : The methods are static.
Method description
* validate(TeamMemberDTO teamMember)
© This method will recelve a TeamMemberDTO object. It should call the respective
validator methods (described below) to validate the team member data and in case of
failed validation, throw exceptions with the corresponding messages as shown in the
table below:
(oiatonFaessage
[employeté|vatestocnVALIO-EMPLOVEED|
+ validateEmployeeld( Integer employeeld)
«The method validates employeetd
© The employeeld should be a six digit positive number.
« Ifthe above condition is satisfied, return true, otherwise return false
3. ProjectServiceimpl class (to be implemented)
‘This is the service class of this application. Implement it using class diagram and description
” below: q
Mark it with appropriate stereotype annotation with value as “projectService"
Instance variable description
* repository should be injected using autowiring,
Method description
+ addProject(ProjectDTO project)
© This method receives a ProjectDTO object, validates it and send to Repository to be
added to database.
© This method invokes validate() of Validator class to validate the employeeld of each
employee.
o If all the details are valid, it should invoke addProject() of ProjectRepository, which in
turn returns an integer value.
« Itretumns the value received in previous step
+ getProjectDetalls(String technology)
«This method return a list of al projects that belong to the received technology.
© It should invoke the getProjectDetalls() of ProjectRepository which returns a list of
Project object.
® filter the list obtained in previous step to get a list of only those projects whose
technology is same as the technology received by this method,EA)
ae
Create and populate a new List using the filtered list, obtained in previous
step.
olf the filtered list is empty, then throw AbcException with message
"Service PROJECTS NOT_FOUND’, else return the List obtained in
previous step.
4, ProjectRepositoryimpl class
‘This is the Repository class of this application and is already implemented.
Method description
+ addProject(ProjectDTO project)
« This method is used to save the project details in database.
+ List getProjectDetails()
© The method return details of all the projects.
5, AbcToTraineeApplication
‘This class Is used to run your Spring Boot application. Implement it using class diagram and
»~ given below: q
Note : The success and error messages should be logged using properties fle.
Instance Variable Description
* Inject the projectService using autowiring.
* Inject the environment using autowiring.
Method description
1. addProject()
+ Invoke addProject() method of ProjectServicelmpl class, which returns an integer for valid
data or throws an exception for invalid data,
The success message should be logged using property as.
"Userinterface PROJECT_ADDED_SUCCESS*
* For following valid values for project details:
ejector: FSADH|
fost 2000
eamsize 5
lecmnology2ed Jara
Payee TED
pojeeame: RobinyA 2.1KB/s ©
ray @ lex.infosysapps.com
feamsize 5
lecmnology3ed Jara
ESEEISS©| Iti Asotin
D> sareeconsny q
« Invoke getProjectDetalls() methad of ProjectServicelmpl class,
+ For valid technology: “Java’, output should be logged in console as:
STOTT TRG 9p)
ee Se me an ee ne
(selayomnrinc, sellsebeeat, sigeionst]|} " ” ° "
* For invalid technology: “Angular”, output should be logged in console as.
Sie -Rcrerammenpceion | cil poi sks allng bck Gott pc
Seok binereme bes | | SEC AGMURM L Srue ance aaate4.4KB/s © Bi
com/en/viev ©
in Spring Boot using default logger
ne
While executing your Spring Boot application, have you seen messages like the ones given
below getting printed on your console?
Licati
main] INFO
revel
Teer Sy
‘Any guess what are these?
‘These are messages logged at INFO level but, you havent written any code for logging in your
application, Then who does this?
This is done by Spring Boot.
‘Spring Boot uses Apache Commons Logging for logging. It provides default configurations for
using Java Util Logging, Log4j2, and Logback as logging implementation. If Spring Boot starters
are used then Logback is used for logging by default,
By default, it logs messages in console at ERROR, WARN, and INFO levels. You can easily
configure logging levels, logging format, and log file location by setting logging related
properties in application properties file.
Configuring Logging Levels
Spring Boot by default, logs messages at ERROR, WARN, and INFO levels, You can also set
the logging levels in application,properties file by setting the property logging level.= where logging-level is one of TRACE, DEBUG, INFO, WARN, ERROR,
FATAL, or OFF. For example, you can set the logging level as INFO for classes in cominfy
package as follows
The root logger can be configured by setting logginglevelroot property in
application properties file.
Configuring Logging Pattern
You can change the logging pattern for console by setting logging.pattern.console property
in application properties file as follows:
Nee CRE