Spring Core&Boot
Spring Core&Boot
Spring Core
endava.com
Dependency injection
Spring Core Spring framework
Spring container
Application context
Beans
Spring configuration
Spring wiring
Filtering beans
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
3
Spring Framework
Spring
4
• simplifies Java development by employing four key strategies:
- lightweight and minimally invasive development with plain old Java objects (POJOs)
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.
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.
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
@Component
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Autowired
private DateTimeService dateTimeService;
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
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
12
13
15
16
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
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)
Annotation-based configuration
@PostConstruct and @PreDestroy
22
@Autowired
public Foo(Baz baz){
this.baz = baz;
}
}
24
Spring wiring
Enabling scanning
@Configuration
@ComponentScan(basePackages = "org.package")
public class AppConfig{
}
25
Often it is preferable to use an aggregation approach, where one @Configuration class logically
imports the bean definitions defined by another.
26
OR
28
@ComponentScan ( includeFilters =
@ComponentScan.Filter(type=FilterType.REGEX,pattern="com\\.baeldung\\.componentscan
\\.springbootapp\\.flowers\\..*"))
public class AppConfig{
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={PersistenceTestConfig.class}
)
@ActiveProfiles("dev")
public class PersistenceTest {
...
}
29
Filtering beans - Conditional beans
30
What is it
Spring Boot What’s new with Spring Boot
Spring Boot vs non-Spring Boot
application
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);
}
}
} 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();
}
}
• 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
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
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).