0% found this document useful (0 votes)
3 views52 pages

CS393 Week2

This document outlines the key concepts and components of developing backend applications using the Spring Framework, focusing on Spring Beans, Inversion of Control (IoC), and Dependency Injection (DI). It covers various methods for creating and configuring beans, including XML, annotation, and Java-based configurations, as well as the lifecycle of the application context. Additionally, it discusses the benefits of DI and different types of injection, such as constructor and setter injection.

Uploaded by

emirhan.benderli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views52 pages

CS393 Week2

This document outlines the key concepts and components of developing backend applications using the Spring Framework, focusing on Spring Beans, Inversion of Control (IoC), and Dependency Injection (DI). It covers various methods for creating and configuring beans, including XML, annotation, and Java-based configurations, as well as the lifecycle of the application context. Additionally, it discusses the benefits of DI and different types of injection, such as constructor and setter injection.

Uploaded by

emirhan.benderli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

CS 393

CS 393
Developing Backend Applications
with Spring Framework

Esma Meral
[email protected]
Week - 2

CS 393 Developing Backend Applications with Spring Framework Esma Meral 1


Outline
1. Spring Beans
2. Instantiating and using a container
3. Inversion of Control and Dependency Injection
4. Some Autowiring Tips

CS 393 Developing Backend Applications with Spring Framework Esma Meral 2


Spring Beans
1. Spring Beans
2. Instantiating and using a container
3. Inversion of Control and Dependency Injection
4. Some Autowiring Tips

CS 393 Developing Backend Applications with Spring Framework Esma Meral 3


What is Java Bean?
●A JavaBean is a Java class that should follow the following
conventions:
▪ It should have a no-arg constructor
▪ It should be Serializable
▪ It should provide methods to set and get the values of the properties, known
as getter and setter methods

CS 393 Developing Backend Applications with Spring Framework Esma Meral 4


What is Spring Bean?
●In Spring, the objects that form the backbone of your application and
that are managed by the Spring IoC container are called beans.
●A bean is an object that is instantiated, assembled, and otherwise
managed by a Spring IoC container.

CS 393 Developing Backend Applications with Spring Framework Esma Meral 5


How to create a bean?
●Three important methods to provide configuration metadata to
the Spring Container
Configuration Data Inversion of Control Container

1.XML Based UserService

@
Bean CustomerRepository
2.Annotation
Definitions
Based
ProductController
3.Java Based

CS 393 Developing Backend Applications with Spring Framework Esma Meral 6


Spring rebooted
●Spring 2.5 introduced annotation-based component-scanning
▪ eliminated a great deal of explicit XML configuration
●Spring 3.0 introduced a Java-based configuration
▪ type-safe and refactorable option to XML.

CS 393 Developing Backend Applications with Spring Framework Esma Meral 7


1.XML based configuration file

<?xml version="1.0" encoding="UTF-8"?>


<beans ... >
<!-- simple bean definitions -->
<bean id="userDAO" class="demo.dao.UserDAO"/>
<bean id="ldapDAO" class="demo.dao.LdapDAO"/>
<bean id="idWS" class="demo.ws.IdWS"/>

<bean id="userService" class="demo.service.UserServiceImpl">


<constructor-arg ref="ldapDAO"/>
<constructor-arg ref="userDAO"/> dependencies
<property name="idWS" ref="idWS"/>
</bean>
</beans>

CS 393 Developing Backend Applications with Spring Framework Esma Meral 8


2.Annotation Based Configuration
Spring Framework Stereotypes:

@Component

@Controller @Repository @Service

@RestController @Controller + @ResponseBody

CS 393 Developing Backend Applications with Spring Framework Esma Meral 9


Example: Annotation Based Configuration

@Component("paymentService")
public class PaymentServiceImpl implements PaymentService {

Application Context
paymentService -> instance of PaymentServiceImpl

CS 393 Developing Backend Applications with Spring Framework Esma Meral 10


3.Java-based Configuration
●Beans can be defined by using Java rather than XML
▪ @Configuration
- source of bean definitions.
- allow inter-bean dependencies to be defined by simply calling other @Bean methods in
the same class.
▪ @Bean
- used to indicate that a method instantiates, configures and initializes a new object to be
managed by the Spring IoC container.
- Same as <bean> element
▪ @Import
- loads @Bean definitions from another configuration class

CS 393 Developing Backend Applications with Spring Framework Esma Meral 11


Example: Java-based Configuration

@Configuration
public class AppConfig {
@Bean
public ProductRepository createProductRepo() {
//Object Creation
ProductRepository repo=new ProductRepository();
repo.setUrl("jdbc:derby://localhost:1527/demodb;create=true");
repo.setUsername("emeral");
repo.setPassword("password");
return repo;
}
}

CS 393 Developing Backend Applications with Spring Framework Esma Meral 12


Component Scanning…

@Configuration
public class Application {…}

NoSuchBeanDefinitionException: No qualifying bean


of type 'com.sample.repo.ProductRepository'
available

CS 393 Developing Backend Applications with Spring Framework Esma Meral 13


…Component Scanning
●@ComponentScan
▪ specify the packages that we want to be scanned
▪ without arguments tells Spring to scan the current package and all of its sub-
packages

@Configuration
@ComponentScan(basePackages ={"com.sample.repo","com.ozyegin.demo"})
public class Application {

CS 393 Developing Backend Applications with Spring Framework Esma Meral 14


Composing Configurations
●@Import Annotation

@Configuration @Configuration
@Import(ConfigA.class) public class ConfigA {
public class ConfigB { @Bean
@Bean public A a() {
public B b() { return new A();
return new B(); }
} }
}

CS 393 Developing Backend Applications with Spring Framework Esma Meral 15


Application context Lifecycle Phases
Initialize Use Destroy

● Prepares for use •Used by clients •Shutdown


● Application services •Application services •Application services
➢ Process client requests ➢ Release any
▪ Are created
➢ Carry out application system resources
▪ Configured ➢ Eligible for
behaviors
▪ May allocate system garbage collection
resources •99.99% of the time is
spent in this phase
● Application is not usable
until this phase is complete

CS 393 Developing Backend Applications with Spring Framework Esma Meral 16


Instantiating and using a container
1. Spring Beans
2. Instantiating and using a container
3. Inversion of Control and Dependency Injection
4. Some Autowiring Tips

CS 393 Developing Backend Applications with Spring Framework Esma Meral 17


Container overview
●ApplicationContext represents the Spring IoC container
●Several Implementations:

ClassPathXmlApplicationContext

FileSystemXmlApplicationContext
ApplicationContext
AnnotationConfigApplicationContext

WebApplicationContext

CS 393 Developing Backend Applications with Spring Framework Esma Meral 18


Instantiating a container
// retrieve configured instance
ApplicationContext ctx=new
AnnotationConfigApplicationContext(Application.class);

ApplicationContext context =
new ClassPathXmlApplicationContext(new String[]
{"services.xml", "daos.xml"});

CS 393 Developing Backend Applications with Spring Framework Esma Meral 19


How Spring Works
XML configuration Java based configuration
<beans … >
<bean id="..." class="...">
</bean> @Configuration
<bean id="..." class="...">
</bean>
<!-- more bean definitions -->
</beans Object Model Configuration
Your Classes

Configuration Spring
Application Context
produces
Context

Fully Configured system


Ready for Use

CS 393 Developing Backend Applications with Spring Framework Esma Meral 20


Configuration Instructions
@Service("newsService") @Repository("newsRepo")
public class NewsServiceImpl implements NewsService { public class NewsRepositoryImpl implements NewsRepository {
@Autowired @Autowired
public NewsServiceImpl(NewsRepository newsRepo) { public NewsRepositoryImpl(DriverManagerDS dataSource) {
this.newsRepo = newsRepo; this.dataSource = dataSource;
} }
} Repository }
Is needed to retrieve and update
current news
@Configuration
public class AppConfig { DataSource
@Bean(name = "dataSource") Is needed to save and read from
public DriverManagerDataSource dataSource() { a database
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}

CS 393 Developing Backend Applications with Spring Framework Esma Meral 21


Create and Use the Application

Java – based Configuration

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

//Lookup the service interface from the context


NewsService newsService = context.getBean("newsService",NewsService.class);

//Use the service


News[] currentNews = newsService.getCurrentNews();

CS 393 Developing Backend Applications with Spring Framework Esma Meral 22


Anatomy of the Application Context
//Create the application context
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

Application Context
transferService

TransferServiceImpl

transferRepository

JdbcTransferRepository

dataSource

DriverManagerDataSource

CS 393 Developing Backend Applications with Spring Framework Esma Meral 23


Using the beans

// retrieve configured instance


TransferService trService = context.getBean("trService", TransferService.class);

// use configured instance


boolean result = trService.transfer("$50", "1", "2");

Simple beans – Just invoke

CS 393 Developing Backend Applications with Spring Framework Esma Meral 24


Beans wrapped in a proxy
●Dynamic proxies created by BeanPostProcessors add behaviors to
your application logic transparently
transfer(“$50”,”1”,”2”)

transfer(“$50”,”1”,”2”)
TransactionInterceptor TransferServiceImpl

begin commit

TransactionInterceptor

CS 393 Developing Backend Applications with Spring Framework Esma Meral 25


Proxies make Spring work

CS 393 Developing Backend Applications with Spring Framework Esma Meral 26


Demo 1

Create and use a simple bean


GreetingService
GreetingServiceImpl

CS 393 Developing Backend Applications with Spring Framework Esma Meral 27


Inversion of Control and Dependency
Injection
1. Spring Beans
2. Instantiating and using a container
3. Inversion of Control and Dependency Injection
4. Some Autowiring Tips

CS 393 Developing Backend Applications with Spring Framework Esma Meral 28


Inversion of Control (IoC)
●Inversion of Control (IoC) is a principle in which an object defines its
dependencies without creating them
●Control flow of a program is inverted:
▪ instead of the programmer controlling the flow of a program, object delegates
the job of constructing and instantiating such dependencies to the external
sources (IoC container, framework, services, other components) take control
of it.

CS 393 Developing Backend Applications with Spring Framework Esma Meral 29


How to implement IoC?
●Several basic techniques to implement inversion of control. These are:
▪ using a factory pattern
▪ using a service locator pattern
▪ using a dependency injection of any given below type:
- a constructor injection
- a setter injection
- an interface injection

CS 393 Developing Backend Applications with Spring Framework Esma Meral 30


Dependency Injection (DI)
●A design pattern which implements IoC principle
●Provides objects that an object needs
▪ Let’s say, class X is dependent on Y. So rather than creating object of Y within
the class “X”, we can inject the dependencies via a constructor or setter
injection.

CS 393 Developing Backend Applications with Spring Framework Esma Meral 31


An Example…
●Let to say that we make some meeting in a hotel.

●Without IoC:
▪ Many people, many jugs of water, many plastic cups.
▪ When somebody wants to drink water, he fills a cup,
drinks it, and throws the cup on the floor.
▪ After an hour or something, we have a floor covered with
plastic cups and water.

CS 393 Developing Backend Applications with Spring Framework Esma Meral 32


…An Example
●With IoC:
▪ We have a waiter who has a glass (Singleton) instead of a plastic cup and he
always serves drinks to the guests
▪ When somebody wants to drink, he gets from waiter glass, drink and return it
back to waiter (Leaving aside the question of the hygienic)
▪ And this is exactly what the IoC container does.
- Instead of let to application create what it need using new keyword (taking plastic cup),
Spring IoC container all of time offer to application the same instance (singleton) of
needed object(glass of water).
▪ Drinking process control is much more effective and economic.

CS 393 Developing Backend Applications with Spring Framework Esma Meral 33


Dependency Injection is Good
●Your object is handed what it needs to work
▪ Frees your object from the burden of resolving its dependencies
▪ Simplifies your code, improves code reusability
●Promotes programming to interfaces
▪ Conceals the implementation details of each dependency
●Improves test-ability
▪ Dependencies can be easily stubbed out for unit testing
●Allows for centralized control over object life-cycle
▪ Opens the door for new possibilities

CS 393 Developing Backend Applications with Spring Framework Esma Meral 34


Reading

https://martinfowler.com/articles/injection.html#InversionOfControl

CS 393 Developing Backend Applications with Spring Framework Esma Meral 35


Dependency Injection Types
●Two major variants:
▪ Constructor-based dependency injection
▪ Setter-based dependency injection

❑Field injection : not really a new injection type


- under the hood, Spring uses reflection to set these values.

CS 393 Developing Backend Applications with Spring Framework Esma Meral 36


Constructor Injection
@Component(“mastercard")
public class MastercardPaymentServiceImpl implements CreditCardPaymentService{

} @Autowired without a
@Qualifier
@Component("visa")
public class VisaPaymentServiceImpl implements CreditCardPaymentService{ matches any instance
CardPaymentService
} regardless of the name.
@Component("paymentService") If there is more than one,
public class PaymentServiceImpl implements PaymentService { we need to qualify it
@Autowired
public PaymentServiceImpl( @Qualifier("visa") CreditCardPaymentService cardPaymentService ) {
...
}
}
CS 393 Developing Backend Applications with Spring Framework Esma Meral 37
Setter Injection
@Component("visa")
public class VisaPaymentServiceImpl implements CreditCardPaymentService{

public class PaymentServiceImpl implements PaymentService {


...
@Resource
@Qualifier("mastercard")
public void setCardPaymentService(
CreditCardPaymentService cardPaymentService){

}
} @Resource requires a @Qualifier
CS 393 Developing Backend Applications with Spring Framework Esma Meral 38
Injecting Scalar Values

@Value("Hi, how are you?")


private String greeting;

equivalent

GreetingService service=new GreetingServiceImpl();


service.setGreeting("Hi, how are you?");

CS 393 Developing Backend Applications with Spring Framework Esma Meral 39


Bean Scopes
●Spring puts each bean instance in a scope
▪ Singleton scope is the default
▪ The “single” instance is scoped by the context itself
▪ By far the most common
●Prototype
▪ A new instance is created each time the bean is referenced
●Session
▪ A new instance is created once per user Http session
●Request @Component("greetingService")
▪ A new instance is created once per Http request @Scope("prototype")
public class
GreetingServiceImpl{…}
CS 393 Developing Backend Applications with Spring Framework Esma Meral 40
Lazy Beans
●Mark singleton beans that are expensive to create and rarely used
lazy
▪ Will not be created until referenced

@Bean
@Lazy
public MyLazyBean lazyBean () {
return new MyLazyBean();
}

CS 393 Developing Backend Applications with Spring Framework Esma Meral 41


Demo 2

IoC & DI

CS 393 Developing Backend Applications with Spring Framework Esma Meral 42


Some Autowiring Tips
1. Spring Beans
2. Instantiating and using a container
3. Inversion of Control and Dependency Injection
4. Some Autowiring Tips

CS 393 Developing Backend Applications with Spring Framework Esma Meral 43


Autowire Need for Disambiguation...
●By default, Spring resolves autowired entries by type.
●If more than one bean of the same type is available in the container,
the framework will throw NoUniqueBeanDefinitionException

CS 393 Developing Backend Applications with Spring Framework Esma Meral 44


Autowire Need for Disambiguation…
@Component("fooFormatter")
public class FooFormatter implements Formatter {
...
}

@Component("barFormatter")
public class BarFormatter implements Formatter {
... NoUniqueBeanDefinition
}
Exception
@Component
public class FooService {

@Autowired
private Formatter formatter;
}
CS 393 Developing Backend Applications with Spring Framework Esma Meral 45
Autowire Need for Disambiguation…
●By using the @Qualifier annotation, eliminate the issue of which bean
needs to be injected.

public class FooService {

@Autowired
@Qualifier("fooFormatter")
private Formatter formatter;
}

CS 393 Developing Backend Applications with Spring Framework Esma Meral 46


Autowire Need for Disambiguation
●Note that we could have also used the @Qualifier annotation on the
Formatter implementing classes, instead of specifying the names in
their @Component annotations, to obtain the same effect:
@Component
@Qualifier("fooFormatter")
public class FooFormatter implements Formatter {
//...
}

CS 393 Developing Backend Applications with Spring Framework Esma Meral 47


@Qualifier vs @Primary…
• @Qualifier @Configuration
• eliminates the issue of public class Config {
which bean needs to be @Bean
injected. public Employee firstEmployee() {
• @Primary return new Employee("John");
• defines a preference }
when multiple beans of @Bean
the same type are @Primary
present public Employee secondEmployee() {
return new Employee("Tony");
}
}
CS 393 Developing Backend Applications with Spring Framework Esma Meral 48
@Qualifier vs @Primary
●If both the @Qualifier and @Primary annotations are present, then
the @Qualifier annotation will have precedence.

CS 393 Developing Backend Applications with Spring Framework Esma Meral 49


@Qualifier vs Autowiring by Name
●Use the name of the field to inject.
●This is the default in case if there are no other hints for Spring

@Autowired
private Formatter fooFormatter;

@Component
public class FooFormatter implements Formatter {
//...
}
CS 393 Developing Backend Applications with Spring Framework Esma Meral 50
Reference

https://www.baeldung.com/spring-qualifier-annotation

CS 393 Developing Backend Applications with Spring Framework Esma Meral 51


Thank you for your attention
For questions:
[email protected]

CS 393 Developing Backend Applications with Spring Framework Esma Meral 52

You might also like