KEMBAR78
2-Core Features of Spring | PDF | Spring Framework | Computer Programming
0% found this document useful (0 votes)
19 views22 pages

2-Core Features of Spring

The document provides an overview of core features of Spring Boot, particularly focusing on autoconfiguration of Spring beans and dependency injection. It explains how Spring Boot simplifies application setup by automatically configuring beans based on classpath settings and the use of starters to add dependencies. Additionally, it discusses customization of application properties and profiles to manage different configurations for various environments.

Uploaded by

armaganuygunn
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)
19 views22 pages

2-Core Features of Spring

The document provides an overview of core features of Spring Boot, particularly focusing on autoconfiguration of Spring beans and dependency injection. It explains how Spring Boot simplifies application setup by automatically configuring beans based on classpath settings and the use of starters to add dependencies. Additionally, it discusses customization of application properties and profiles to manage different configurations for various environments.

Uploaded by

armaganuygunn
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/ 22

BIM308 – Web Server

Programming
2- Core Features of Spring Boot
Autoconfiguring Spring beans
• Whenever a Spring Framework application starts up, whether or not
Spring Boot is involved, it creates a container of sorts. Various Java
beans that are registered with Spring Framework’s application context
are known as Spring beans.
Tip
What’s a Java bean? Java beans are objects that follow a specific pattern: all the fields are private;
they provide access to their fields through getters and setters, they have a no-argument constructor,
and they implement the Serializable interface.
Autoconfiguring Spring beans
For example, an object of the Video type with name and location fields would set those two fields
to private and offer getName(), getLocation(), setName(), and setLocation() as the ways to mutate the
state of this bean.
On top of that, it would have a no-argument Video() constructor call. It’s mostly a convention. Many
tools provide property support by leveraging the getters and setters.
The requirement to implement the Serializable interface, though, is not as tightly enforced.
Autoconfiguring Spring beans
Spring Framework has a deep-seated concept known as dependency injection (DI), where a Spring
bean can express its need for a bean of some other type. For example, a BookRepository bean may
require a DataSource bean:

@Bean
public BookRepository bookRepository(DataSource dataSource)
{
return new BookRepository(dataSource);
}

1. bookRepository needs a DataSource


2. Ask the application context for a DataSource.
3. The application context either has it or will go create one and return it.
4. bookRepository executes its code while referencing the app context’s DataSource.
5. BookRepository is registered in the application context under the name bookRepository.
Autoconfiguring Spring beans
1. bookRepository needs a DataSource
2. Ask the application context for a DataSource.
3. The application context either has it or will go create one and return it.
4. bookRepository executes its code while referencing the app context’s DataSource.
5. BookRepository is registered in the application context under the name bookRepository.
The application context will ensure all Spring beans needed by the application are created and properly injected into
each other. This is known as wiring.
Why all this instead of a handful of new operations in various class definitions?
• Simple. For the standard situation of powering up our app, all the beans are wired together as expected.
For a test case, it’s possible to override certain beans and switch to stubbed or mocked beans.
For cloud environments, it’s easy to find all DataSource and replace them with beans that link to bound data services.
By removing the new operation from our example BookRepository, and delegating that responsibility to the application
context, we open the door to flexible options that make the whole life cycle of application development and
maintenance much easier.
We’ll explore how Spring Boot heavily leverages the Spring Framework’s ability to inject beans based on various
circumstances throughout this semester. It is important to realize that Spring Boot doesn’t replace the Spring
Framework but rather highly leverages it.
Now that you know what an application context is, it is time to dive into the many ways Spring Boot makes use of
it through autoconfiguration.
Exploring autoconfiguration policies in Spring
Boot
Spring Boot comes with a fistful of autoconfiguration policies. These are classes that
contain @Bean definitions that are only registered based on certain conditional circumstances. Perhaps
an example is in order?

If Spring Boot detects the class definition of DataSource somewhere on the classpath, a class found inside
any Java Database Connectivity (JDBC) driver, it will activate its DataSourceAutoConfiguration.
This policy will fashion some version of a DataSource bean. This is driven by the @ConditionalOnClass({
DataSource.class }) annotation found on that policy.
Inside DataSourceAutoConfiguration are inner classes, each driven by various factors. For example, some
classes will discern whether or not we have used an embedded database such as H2 compared to a
pooled JDBC asset
Exploring autoconfiguration policies in Spring
Boot
The need for us to configure an H2 DataSource is removed. A small piece of infrastructure that is often
the same across a multitude of applications is taken off our plate and instead managed by Spring Boot.
And we can move more quickly toward writing business code that uses it.

Spring Boot autoconfiguration also has smart ordering built in, ensuring beans are added properly.
Don’t worry! Using Spring Boot doesn’t depend on us having to know this level of detail.

Most of the time, we don’t have to know what Spring Boot is up to. It’s designed to do the right thing
when various things are added to the build configuration.

The point is that many features, such as servlet handlers, view resolvers, data repositories, security
filters, and more are activated, simply based on what dependencies we add to the build file.
Exploring autoconfiguration policies in Spring
Boot
Some beans are created based on the classpath settings. But if a certain bean definition is detected inside
our code, the autoconfiguration won’t kick in.

For instance, if we put something such as H2 in our classpath but define a DataSource bean and register it
in the application context, Spring Boot will accept our DataSource bean over theirs.

No need to tell Spring Boot about it. Just create your own bean as you see fit, and Spring Boot will pick it
up and run with it!

This may sound low-level, but Spring Boot’s autoconfiguration feature is transformational. If we focus on
adding all the dependencies our project needs, Spring Boot will, as stated earlier, do what’s right.
Exploring autoconfiguration policies in Spring
Boot
Some of the autoconfiguration policies baked into Spring Boot
•Spring AMQP: Communicate asynchronously using an Advanced Message Queueing Protocol (AMQP) message broker
•Spring AOP: Apply advice to code using Aspect-Oriented Programming
•Spring Batch: Process large volumes of content using batched jobs
•Spring Cache: Ease the load on services by caching results
•Data store connections (Apache Cassandra, Elasticsearch, Hazelcast, InfluxDB, JPA, MongoDB, Neo4j, Solr)
•Spring Data (Apache Cassandra, Couchbase, Elasticsearch, JDBC, JPA, LDAP, MongoDB, Neo4j, R2DBC, Redis, REST): Simplify data
access
•Templating engines (Freemarker, Groovy, Mustache, Thymeleaf)
•Serialization/deserialization (Gson and Jackson)
•Spring JDBC: Simplify accessing databases through JDBC
•Spring JMS: Asynchronous through Java Messaging Service (JMS)
•Spring JMX: Manage services through Java Management Extension (JMX)
•jOOQ: Query databases using Java Object Oriented Querying (jOOQ)
•Apache Kafka: Asynchronous messagingLiquibase: Database schema management
•Spring Validation: Bean validation
•Spring MVC: Spring’s workhorse for servlet-based web apps using the Model-View-Controller (MVC) paradigm
•Spring Web Services: Simple Object Access Protocol (SOAP)-based services
Adding portfolio components using Spring
Boot starters
How About adding H2? Or Spring MVC? Maybe Spring Security?
If you add org.springframework.boot:spring-boot-starter-web to the project, it will
activate Spring MVC:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

If you add org.springframework.boot:spring-boot-starter-data-jpa to the project, it will activate


Spring Data JPA:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Adding portfolio components using Spring
Boot starters
There are 50 different Spring Boot starters, each with the perfect coordinates to various bits of the
Spring portfolio and other related third-party libraries.
But the problem isn’t just a shortcut to adding Spring MVC to classpath. There’s little difference
between org.springframework.boot:spring-boot-starter-web and org.springframework:spring-webmvc.

Spring MVC versus Spring Web? Spring Framework has three artifacts involving web applications:
Spring Web, Spring MVC, and Spring WebFlux.

Spring MVC is servlet-specific bits.

Spring WebFlux is for reactive web app development and is not tied to any servlet-based contracts.

Spring Web contains common elements shared between Spring MVC and Spring WebFlux. This mostly
includes the annotation-based programming model Spring MVC has had for years. This means that the
day you want to start writing reactive web apps, you don’t have to learn a whole new paradigm to
build web controllers.
Adding portfolio components using Spring
Boot starters
If we added spring-boot-starter-web, this is what we’d need:
•Spring MVC and the associated annotations found in Spring Web. These are the Spring Framework
bits that support servlet-based web apps.
•Jackson Databind for serialization and deserialization to and from JSON.
•An embedded Apache Tomcat servlet container.
•Core Spring Boot starter.
•Spring Boot.
•Spring Boot Autoconfiguration.
•Spring Boot Logging.
•Jakarta annotations.
•Spring Framework Core.
•SnakeYAML to handle YAML Ain’t Markup Language (YAML)-based property files.
Customizing the setup with configuration
properties
Assuming we were building a web app and selected Spring MVC’s spring-boot-starter-web, it would
activate embedded Apache Tomcat as the servlet container of choice.
Spring Boot is forced to make a lot of assumptions.
For example, what port should it listen on? What about the context path? Secure Sockets Layer (SSL)?
Threads? ect.

Spring Boot introduces configuration properties as a way to plug property settings into any Spring bean.
Spring Boot may load certain properties with default values, but we have the opportunity to override
them.
The simplest example is the first property mentioned earlier in this section – the server port.
Spring Boot launches with a default port in mind, but we can change it. This can be done by first adding
an application.properties file to our src/main/resources folder.
Inside that file, we must merely add the following:
server.port=9000
Customizing the setup with configuration
properties
This Java property file contains a list of key-value pairs separated by an equals sign (=). The left-hand
side contains the key (server.port) and the right-hand side contains the value (9000).
When a Spring Boot application launches, it will look for this file and scan in all its property entries, and
then apply them. And with that, Spring Boot will switch from its default port of 8080 to port 9000.
Spring Boot has alternative servlet container starters, including Jetty and Undertow.
What’s important is knowing that no matter which servlet container we use, the servlet.port property
will be applied properly to switch the port the servlet will serve web requests on.

There are container-specific property settings if we needed that level of control. But generalized
properties make it easy for us to select our preferred container and move to a port and context path of
choice.

The point of Spring Boot property settings isn’t about servlet containers. It’s about creating opportunities
to make our applications flexible at runtime.
Creating custom properties
Configuration properties can be applied to any Spring bean. This applies not just to Spring Boot’s autoconfigured
beans, but to our own Spring beans!

@Component
@Component is Spring Framework’s annotation to
@ConfigurationProperties(prefix = "my.app")
automatically create an instance of this class when the
public class MyCustomProperties {
application starts and register it with the application
// if you need a default value, assign it here or the
context.
constructor
•@ConfigurationProperties is a Spring Boot annotation that
private String header;
labels this Spring bean as a source of configuration
private String footer;
properties. It indicates that the prefix of such properties
// getters and setters
will be my.app.
}

The class itself must adhere to standard Java bean property rules. It will create various fields and include proper
getters and setters – in this case, getHeader() and getFooter().
application.properties:
my.app.header=Learning Spring Boot 3
my.app.footer=Find all the source code at https://github.com/PacktPublishing/Learning-Spring-Boot-3.0
Externalizing application configuration
Spring Boot not only looks for that application.properties tucked inside our JAR file upon startup. It will
also look directly in the folder from where we run the application to find any application.properties files
there and load them.

We can deliver our JAR file along with an application.properties file right beside it as an immediate way
to override pre-baked properties (ours or Spring Boot’s!).

Spring Boot also supports profiles.


What are profiles? We can create profile-specific property overrides. A good example would be one
configuration for the development environment, but a different one for our test bed, or production.
In essence, we can create variations of application.properties, as shown here:
•application-dev.properties is a set of properties applied when the dev profile is activated
•application-test.properties is applied when the test profile is applied
•application.properties is always applied, so it could be deemed the production environment
Externalizing application configuration
application.properties:
my.app.databaseUrl=https://user:pass@production-server.com:1234/prod/

application-test.properties:
my.app.databaseUrl=http://user:pass@test-server.com:1234/test/

To activate this override, simply include -Dspring.profiles.active=test as an extra argument to the Java
command to run our app.

Since production is the end state of an application, it’s usually best practice to let application.properties be the
production version of property settings. Use other profiles for other environments or configurations.
Externalizing application configuration
There are many more ways to bind property settings into a Spring Boot application.
Ordered from lowest priority to highest priority
•Default properties provided by Spring Boot’s SpringApplication.setDefaultProperties() method.
•@PropertySource-annotated @Configuration classes.
•Config data (such as application.properties files).
•A RandomValuePropertySource that has properties only in random.*.
•OS environment variables.
•Java system properties (System.getProperties()).
•JNDI attributes from java:comp/env.
•ServletContext init parameters.
•ServletConfig init parameters.
•Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property).
•Command-line arguments.
•The properties attribute on your tests. This is available with the @SpringBootTest annotation and also slice-based testing (which
we’ll cover later in Testing with Spring Boot).
•@TestPropertySource annotations on your tests.
•DevTools global settings properties (the $HOME/.config/spring-boot directory when Spring Boot DevTools is active).
Externalizing application configuration
Config files are considered in the following order (ordered from lowest priority to highest priority):
•Application properties packaged inside your JAR file.
•Profile-specific application properties inside your JAR file.
•Application profiles outside your JAR file.
•Profile-specific application properties outside your JAR file.
Configuring property-based beans
Properties aren’t just for providing settings. They can also govern which beans are created and when.
The following code is a common pattern for defining beans:
@Bean
@ConditionalOnProperty(prefix="my.app", name="video")
YouTubeService youTubeService() {
return new YouTubeService();
}
•@Bean is Spring’s annotation, signaling that the following code should be invoked when creating an application
context and the created instance is added as a Spring bean
•@ConditionalOnProperty is Spring Boot’s annotation to conditionalize this action based on the existence of the
property
If we set my.app.video=youtube, then a bean of the YouTubeService type will be created and injected into the
application context.
In this scenario, if we define my.app.video with any value, it will create this bean.
If the property does not exist, then the bean won’t be created. This saves us from having to deal with profiles.
Configuring property-based beans
@Bean
@ConditionalOnProperty(prefix="my.app", name="video", havingValue="youtube")
YouTubeService youTubeService() {
return new YouTubeService();
}
@Bean
@ConditionalOnProperty(prefix="my.app", name="video", havingValue="vimeo")
VimeoService vimeoService() {
return new VimeoService();
}

•@Bean, like before, will define Spring beans to be created and added to the application
context
•@ConditionalOnProperty will conditionalize these beans to only be created if the
named property has the stated values
If we set my.app.video=youtube, a YouTubeService will be created. But if we were to set my.app.video=vimeo,
a VimeoService bean would be created instead.
References
• https://github.com/PacktPublishing/Learning-Spring-Boot-3.0-Third-
Edition

You might also like