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

Spring Core&Boot

The document discusses Spring Core, which is a framework that simplifies Java development through dependency injection, loose coupling, declarative programming, and reducing boilerplate code. It describes key Spring concepts like the Spring container, which manages object lifecycles; beans, which are objects managed by the container; and the application context, which loads bean definitions and wires objects together. It also covers Spring configuration through XML or annotations and the lifecycle of beans in the Spring container.

Uploaded by

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

Spring Core&Boot

The document discusses Spring Core, which is a framework that simplifies Java development through dependency injection, loose coupling, declarative programming, and reducing boilerplate code. It describes key Spring concepts like the Spring container, which manages object lifecycles; beans, which are objects managed by the container; and the application context, which loads bean definitions and wires objects together. It also covers Spring configuration through XML or annotations and the lifecycle of beans in the Spring container.

Uploaded by

Alina Ane
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

QUALITY. PRODUCTIVITY. INNOVATION.

Spring Core

endava.com
 Dependency injection
Spring Core  Spring framework
 Spring container
 Application context
 Beans
 Spring configuration
 Spring wiring
 Filtering beans

2 QUALITY. PRODUCTIVITY. INNOVATION.


Dependency Injection

In software engineering, dependency injection is a software design pattern that implements


inversion of control for resolving dependencies.

Traditionally, each object is responsible for obtaining its own references to the objects it
collaborates with (its dependencies). This can lead to highly coupled and hard-to-test code.

With DI, objects are given their dependencies at creation time by some third party that
coordinates each object in the system. Objects aren’t expected to create or obtain their
dependencies.
3

public class TextEditor { public class TextEditor {

private SpellChecker checker; private IocSpellChecker checker;

public TextEditor() { public TextEditor(IocSpellChecker checker) {


this.checker = new SpellChecker(); this.checker = checker;
} }
} }

3
Spring Framework

Spring

• open source framework

• was created to address the complexity of enterprise application development

4
• simplifies Java development by employing four key strategies:

- lightweight and minimally invasive development with plain old Java objects (POJOs)

- loose coupling through dependency injection and interface orientation

- declarative programming through aspects

- boilerplate reduction through aspects and templates

4 QUALITY. PRODUCTIVITY. INNOVATION.


Spring Framework

IOC (Inversion of Control) container: Framework code invokes application code during an operation
and ask for application specific information instead of application calling the Framework code
directly, hence control is inverted. An example of IOC is Template pattern via sub-classing. Spring IOC
provides annotations based IOC as well. 
DI (Dependency Injection) : Instance of Service implementations are injected into a target Object's
variable/field (where variable/field is ideally of an interface type) via Constructors/Setters instead of
target Object creating the concrete implementations themselves. Hence, this approach enabled
application objects being POJO which can be used in different environment and with different
5
implementations of services. 

AOP (Aspect-Oriented Programming) : This allows separation of cross-cutting concerns by adding


behaviors (aspects) to the application code instead of application involving into those concerns itself.
This enables application to be modular instead of mixing different concerns to a single place. The
examples are Transaction management, logging etc. 

Lightweight Alternative to Java EE : Spring is lightweight solution for building enterprise application
using POJO. It can be used in servlet container (e.g. Tomcat server) and doesn't require an
Application server.

5 QUALITY. PRODUCTIVITY. INNOVATION.


Spring container

In a Spring-based application, your application objects live in the Spring container.


The container is at the core of the Spring Framework. Spring’s container uses DI to
manage the components that make up an application.
Objects are managed by the container: instantiation, lifecycle and destruction
This includes creating associations between collaborating components.
As such, these objects are cleaner and easier to understand, they support reuse, and they’re easy
to unit test
6 will not be managed by the container
There can be objects outside the container, but they

6 QUALITY. PRODUCTIVITY. INNOVATION.


Spring container

There’s no single Spring container. Spring comes


with several container implementations that
can be categorized into two distinct types:
1. Bean factory
2. Application context
7

7 QUALITY. PRODUCTIVITY. INNOVATION.


Application context

Application Context
• In a Spring application, an application context loads bean definitions and wires them together
• It is fully responsible for the creation and wiring of the objects that make up the application
• Spring comes with several implementations of its application context, each primarily differing
only in how they load their configuration

Spring provides several implementation of the Application


8 Context:
• AnnotationConfigApplicationContext —Loads a Spring application context from one or more
Java-based configuration classes
• AnnotationConfigWebApplicationContext —Loads a Spring web application context from one or
more Java-based configuration classes
• ClassPathXmlApplicationContext - Loads a context definition from one or more XML files located
in the classpath, treating context-definition files as classpath resources
• FileSystemXmlApplicationContext —Loads a context definition from one or more XML files in the
filesystem
• XmlWebApplicationContext —Loads context definitions from one or more XML files contained in
a web application

8 QUALITY. PRODUCTIVITY. INNOVATION.


Application context

@Component
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);

@Autowired
private DateTimeService dateTimeService;

public static void main(String[] args) { 9


var ctx = new AnnotationConfigApplicationContext();
ctx.scan("com.zetcode");
ctx.refresh();
var bean = ctx.getBean(Application.class);
bean.run();
ctx.close();
}

public void run() {logger.info("Current date: {}", dateTimeService.getDate()); }


}

9 QUALITY. PRODUCTIVITY. INNOVATION.


Beans

Definition
A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC
container.
The bean definition contains the information called configuration metadata which is needed for the
container to know the followings:
1. How to create a bean
2. Bean's lifecycle details 10
3. Bean's dependencies

10 QUALITY. PRODUCTIVITY. INNOVATION.


Beans

Beans – scopes
In Spring, bean scope is used to decide which type of bean instance should be
returned from Spring container back to the caller

• Singleton – only one instance of bean per spring container ( Default scope)
• Prototype – a new instance every time11a bean is requested
• Request – a single bean instance per HTTP request
• Session – single bean instance per HTTP session
• Global-session – single bean instance per global HTTP session

11 QUALITY. PRODUCTIVITY. INNOVATION.


Beans
Beans lifecycle - A bean goes through several steps between creation and destruction in the Spring
container. Each step is an opportunity to customize how the bean is managed in Spring.

12

12 QUALITY. PRODUCTIVITY. INNOVATION.


Beans

Beans lifecycle - useful links:


https://howtodoinjava.com/spring-core/spring-bean-life-cycle/
https://howtodoinjava.com/spring-core/how-to-create-spring-bean-post-processors

13

13 QUALITY. PRODUCTIVITY. INNOVATION.


Beans
Beans lifecycle
Initialization callbacks
InitializingBean interface - allows a bean to perform initialization work after all necessary properties
on the bean have been set by the container
public class AnotherExampleBean implements InitializingBean {
public void afterPropertiesSet() { // do some initialization work }
}
Recommended to use @PostConstruct method annotation instead
14
Destruction callbacks
DisposableBean interface - allows a bean to get a callback when the container containing it is
destroyed
public class AnotherExampleBean implements DisposableBean {
public void destroy() { // do some destruction work (like releasing pooled connections)}
}
Recommended to use @PreDestroy method annotation instead

14 QUALITY. PRODUCTIVITY. INNOVATION.


Spring configuration
Spring configuration metadata is to tell Spring container how to initiate, configure, wire and
assemble the application specific objects. 
XML-based configuration

15

Annotation-based configuration (Spring 2.5)


@Required,  @Autowired, @Qualifier, @Component, @Controller, @Service, @Scope, @Resource,
Java-based configuration (starting with Spring 3.0)
@Configuration, @Bean

15 QUALITY. PRODUCTIVITY. INNOVATION.


Spring configuration

16

16 QUALITY. PRODUCTIVITY. INNOVATION.


Spring configuration

Annotation-based configuration
Instead of using XML to describe a bean wiring, you can move the bean configuration into the
component class itself by using annotations on the relevant class, method, or field declaration
Annotation injection is performed before XML injection, thus the latter configuration will
override the former for properties wired through both approaches.
Annotation wiring is not turned on in the Spring container by default
This can be done by adding <context:annotation-config/>
17 element from Spring’s context
configuration namespace
<context:component-scan/> can also do what <context:annotation-config/> does but
<context:component-scan/> also scans packages to find and register beans within the application
context
@Required
The @Required annotation applies to bean property setter methods.
Indicates that the affected bean property must be populated at configuration time
The container throws an exception if the affected bean property has not been populated

17 QUALITY. PRODUCTIVITY. INNOVATION.


Spring configuration

Annotation-based configuration
@Autowired
The @Autowired annotation can apply to bean property setter methods, non-setter methods,
constructor and properties.
@Qualifier
The @Qualifier annotation along with @Autowired can be used to remove the confusion by
specifying which exact bean will be wired if there are
18 2 beans implementation of the same interface.
JSR-250 Annotations (Java SE Common Annotations)
Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and
@PreDestroy annotations.
@Component
Is a general-purpose stereotype annotation indicating that the class is a Spring component
@Repository, @Service and @Controller
Are specializations of @Component for more specific use cases ( data repository, service
and a MVC controller)

18 QUALITY. PRODUCTIVITY. INNOVATION.


Spring configuration

Annotation-based configuration
@PostConstruct and @PreDestroy

public class CachingMovieLister {


@PostConstruct
public void populateMovieCache() {// populates the movie cache upon initialization...}
19
@PreDestroy
public void clearMovieCache() { // clears the movie cache upon destruction...}
}

19 QUALITY. PRODUCTIVITY. INNOVATION.


Spring configuration

Annotation based configuration


@Scope
@Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
@Component
public class MovieFinderImpl implements MovieFinder {
// ... 20
}

20 QUALITY. PRODUCTIVITY. INNOVATION.


Spring configuration

Java based configuration


Annotating a class with the @Configuration indicates that the class can be used by the Spring
IoC container as a source of bean definitions.
The @Bean annotation tells Spring that a method annotated with @Bean will return an object
that should be registered as a bean in the Spring application context.
Basic example:
@Configuration
public class HelloWorldConfig {
21
@Bean
public HelloWorld helloWorld(){
return new HelloWorld();
}
}
Equivalent to:
<beans>
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld" />
</beans>

21 QUALITY. PRODUCTIVITY. INNOVATION.


Spring configuration

22

@Configuration If no “name” is provided, the default name will


be the name of the method.
public class AppConfig {

The initMethod/destroyMethod are deprecated


@Bean(name = "myBean")
since Spring supports JSR-250.
public MyBean createBean() {
Instead we can annotate bean's methods with
...... @PostConstruct and @PreDestroy
}
}

22 QUALITY. PRODUCTIVITY. INNOVATION.


Spring configuration

Java based configuration


Accessing the application context - ApplicationContextAware

public class CommandManager implements ApplicationContextAware {


private ApplicationContext applicationContext;
public Object process(Map commandState) {
23
// process and execute a command
}

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {


this.applicationContext = applicationContext;
}
}

23 QUALITY. PRODUCTIVITY. INNOVATION.


Spring wiring
Automatic wiring beans

@Component Component Scanning - Spring automatically


public class Foo{
discovers beans to be created in the
application context
@Autowired Autowiring - Spring automatically satisfies
private Bar pub; bean dependencies
private Baz baz;

@Autowired
public Foo(Baz baz){
this.baz = baz;
}
}

24
Spring wiring

Enabling scanning
@Configuration
@ComponentScan(basePackages = "org.package")
public class AppConfig{
}

25

25 QUALITY. PRODUCTIVITY. INNOVATION.


Spring wiring
@Import – the alternative way to wire beans:

Often it is preferable to use an aggregation approach, where one @Configuration class logically
imports the bean definitions defined by another.

26

26 QUALITY. PRODUCTIVITY. INNOVATION.


Filtering beans

It is more than once wanted to ignore certain beans in certain situations.


Spring can help you with that as well!
• Exclude/Include filters of @ComponentScan
• Profiles
• Conditional Beans
27

27 QUALITY. PRODUCTIVITY. INNOVATION.


Filtering beans – Exclude/include
filters
@ComponentScan(excludeFilters = @ComponentScan.Filter(type =
FilterType.ASSIGNABLE_TYPE, value = Rose.class))
public class AppConfig{
}

OR
28

@ComponentScan ( includeFilters =
@ComponentScan.Filter(type=FilterType.REGEX,pattern="com\\.baeldung\\.componentscan
\\.springbootapp\\.flowers\\..*"))
public class AppConfig{
}

28 QUALITY. PRODUCTIVITY. INNOVATION.


Filtering beans - Profiles

@Configuration You can configure beans to be created only on


specific Spring profiles and make your life a lot
@Profile("prod")
easier.
public class ProductionProfileConfig {
@Bean
public DataSource dataSource() {
….
}
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={PersistenceTestConfig.class}
)
@ActiveProfiles("dev")
public class PersistenceTest {
...
}

29
Filtering beans - Conditional beans

@Bean As you can see, @Conditional is given a Class


that specifies the condition—in this
@Conditional(MagicExistsCondition.class)
case, MagicExistsCondition. @Conditional
public MagicBean magicBean() { comes paired with a Condition interface:
return new MagicBean();
}

public interface Condition {


boolean matches(ConditionContext ctxt,
AnnotatedTypeMetadata metadata);
}

30
 What is it
Spring Boot  What’s new with Spring Boot
 Spring Boot vs non-Spring Boot
application

31 QUALITY. PRODUCTIVITY. INNOVATION.


Spring Boot – What is it

• Spring Boot provides a good platform for Java developers to develop a


stand-alone and production-grade spring application that you can just
run.
• You can get started with minimum configurations without the need for an
entire Spring configuration setup.
• Advantages: 32
• Avoids complex XML configuration in Spring
• Provides a flexible way to configure Java Beans, XML
configurations, and Database Transactions.
• Develops a production ready Spring applications in an easier way
• Reduces the development time and run the application
independently
• Offers an easier way of getting started with the application
• It provides a powerful batch processing and manages REST
endpoints.

32 QUALITY. PRODUCTIVITY. INNOVATION.


Spring Boot – What’s new

• Spring Boot automatically configures your application based on the


dependencies you have added to the project by
using @EnableAutoConfiguration annotation. For example, if MySQL
database is on your classpath, but you have not configured any database
connection, then Spring Boot auto-configures an in-memory database.
• The entry point of the spring boot application is the class
contains @SpringBootApplication annotation and the main method.
• Spring Boot automatically scans all the
33 components included in the project by
using @ComponentScan annotation.

33 QUALITY. PRODUCTIVITY. INNOVATION.


Spring Boot – What’s new
• If you added @SpringBootApplication annotation to the class, you do not
need to add the @EnableAutoConfiguration,
@ComponentScan and @SpringBootConfiguration.
• If no @ComponentScan is specified or it is not specified which packages to
scan, a default is used to scan all bean from the package where the main
application is. (where @SpringBootApplication/@ComponentScan is put)

import org.springframework.boot.SpringApplication;
34
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

34 QUALITY. PRODUCTIVITY. INNOVATION.


Spring Boot vs non-Spring Boot
application
@ComponentScan({"com.package1","com.package2.springboot.somethingelse"})
@SpringBootApplication
public class SpringbootIn10StepsApplication {
public static void main(String[] args) {
ApplicationContext applicationContext = SpringApplication.run(SpringbootIn10StepsApplication.class, args);
for (String name : applicationContext.getBeanDefinitionNames()) {
System.out.println(name);
}
}
35

} VS
@ComponentScan({"com.in28minutes.package1","com.in28minutes.package2"})
@Configuration
public class SpringConfiguration {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(SpringConfiguration.class);
context.getBean(Client.class).showData();
}
}

35 QUALITY. PRODUCTIVITY. INNOVATION.


Questions?
36

36 QUALITY. PRODUCTIVITY. INNOVATION.


Some more useful links

• https://www.logicbig.com/tutorials/spring-framework/spring-core.html
• https://www.baeldung.com/spring-component-scanning
• http://zetcode.com/spring/annotationconfigapplicationcontext/
• https://www.tutorialspoint.com/spring_boot/spring_boot_introduction.htm
• https://www.springboottutorial.com/spring-boot-and-component-scan

37

37 QUALITY. PRODUCTIVITY. INNOVATION.


Exercises

1. Define an article settings model that has various properties such as font size, font color, etc
2. Make various implementations of an article editor that prints a text with the attributes that it
has (these will be inside the implementations, in various combinations – one that has the
dependencies provided from outside the class, one that defines them inside the class, one that
mixes these)
3. Use post processing, pre destruction operations on bean by using the necessary annotations
4. Use the profiles annotations (have an implementation for “dev” and another for “test”) and also
use a filtering bean condition 38

5. Use the prototype bean scope


6. Use the @Qualifer annotation for specifying to spring which bean to autowire.
On the above exercises make sure to use @Autowired on field, setter and constructor. Also try to
get a bean directly from the application context.

38 QUALITY. PRODUCTIVITY. INNOVATION.


Exercises

1. Update what you have done so far to use the features that Spring provides with Spring Boot:
1.Define your beans in configuration classes: Use @ComponentScan and @Import. Note that beans are
registered in the application context by component scan only if the class is annotated with an
appropriate annotation.
2.Use a bean with scope @Prototype.
3.Define a bean by using @Bean inside a @Configuration class.
4.Use @PostConstruct/@PreDestroy annotations and InitializingBean/DisposableBean interfaces.
5.Use the @Qualifer annotation for specifying to spring which bean to autowire (create 2 beans that
implements the same interface) 39
6.Use a method to filter beans: @Profile, Exclude/Include, Conditional Beans

On the above exercises make sure to use @Autowired on field, setter and constructor. Also try to get a
bean directly from the application context (ApplicationContext is a bean already registered in Spring).

39 QUALITY. PRODUCTIVITY. INNOVATION.


Thank you!

Iulia Bindar Andrei Aroșoaie


Software Developer Software Developer
[email protected] [email protected]
gyulia_b en_aarosoaie

40 QUALITY. PRODUCTIVITY. INNOVATION.

You might also like