Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Spring Boot Material

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8
At a glance
Powered by AI
Some of the key takeaways from the document are that Spring Boot simplifies development of Spring applications and provides features like auto-configuration and embedded servlet containers. It also discusses how Spring Boot starters simplify dependency management.

Some of the main advantages of using Spring Boot are easy dependency management through starters, automatic configuration of commonly used beans, and use of an embedded servlet container without needing to deploy the application externally.

Spring Boot simplifies dependency management through the use of starters which aggregate common groupings of dependencies into a single artifact. This avoids the need to manually configure all dependencies in the pom.xml file.

Real-time Approach K.

RAMESH

SPRING BOOT
K.RAMES
H
ASPIRE Technologies
#501, 5th Floor, Mahindra Residency, Maithrivanam Road, Ameerpet, Hyderabad

Ph: 07799 10 8899, 07799 20 8899

E-Mail:ramesh@java2aspire.com website: www.java2aspire.com

1
Real-time Approach K.RAMESH

SPRING BOOT
Without spring boot the problems are:
1) We need to hunt for all the compatible libraries for the specific Spring version and configure them.
2) Most of the times we configure the DataSource, EntitymanagerFactory,TransactionManager, etc beans
in the same way.

3) Similarly we configure Spring MVC beans like ViewResolver, MessageSource etc in the same way most of
the times.

With Spring Boot the advantages are:


1) Easy dependency management because of Spring Boot Starters.
2) Automatic configuration for most of the commonly used beans such as DataSource,
TransactionTemplate, DispatcherServlet, ViewResolver, HandlerMappig, etc using customizable
properties. We need to enable auto configuration by adding either @EnableAutoConfiguraiton or
@SpringBootApplication.

3) Embedded Servlet Container


Spring-boot-starter-web pulls the spring-boot-starter-tomcat automatically which starts tomcat as a
embedded container. So we don’t have to deploy our application on any externally installed tomcat
server.

Spring Boot newly added in Spring 4 and offers following main features:
1) Spring Boot Starters
Spring Boot starters aggregate common groupings of dependencies into single dependency that can be
added to a project’s Maven or Gradle build.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Without Spring Boot, we need to configure all the dependencies required in our pom.xml.

2
Real-time Approach K.RAMESH

As web is selected, spring-boot-starter-web adds all dependencies required for a Spring MVC project. It
also includes dependencies to Tomcat as an embedded HTTP listener.

The parent element is one of the interesting aspects in the pom.xml file.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
</parent>
The advantage of using the spring-boot-starter-parent POM file is that developers need not worry about
finding the right compatible versions of different libraries such as Spring, Jersey, JUnit, Hibernate,
Jackson, and so on. The starter POM file itself does not add JAR dependencies to the project. Instead, it
will only add library versions. Subsequently, when dependencies are added to the POM file, they refer to
the library versions from this POM file. A snapshot of some of the properties are as shown as follows:
<spring-boot.version>1.3.5.BUILD-SNAPSHOT</spring-boot.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<jackson.version>2.6.6</jackson.version>
<jersey.version>2.22.2</jersey.version>
<logback.version>1.1.7</logback.version>
<spring.version>4.2.6.RELEASE</spring.version>
<spring-data-releasetrain.version>Gosling-SR4</spring-data-releasetrain.version>
<tomcat.version>8.0.33</tomcat.version>

2) Autoconfiguration
Spring Boot provides ‘spring-boot-autoconfigure’ module (spring-boot-autoconfigure-<version>.jar)
which contains many configuration classes to autoconfigure beans. The above jar file contains META-
INF/spring.factories file which contains list of autoconfigure classes.
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\

Since spring boot provides many autoconfigure classes hence reduces the complexity of configuration.
Spring Boot auto-configuration is a runtime (more accurately, application startup-time) process that
considers several factors to decide what Spring configuration should and should not be applied. For
example, Is Spring’s JdbcTemplate available on the classpath? If so and if there is a DataSource bean,
then auto-configure a JdbcTemplate bean.
3
Real-time Approach K.RAMESH

Example:
@Configuration
@ConditionalOnClass({ DataSource.class, JdbcTemplate.class })
public class JdbcTemplateAutoConfiguration {

The @EnableAutoConfiguration enables the magic of auto configuration.

Spring-Boot checks tomcat-jdbc (default), HikariCP, Commons DBCP and Common DBCP2 in this
sequence order i.e., Spring Boot checks the availability of the following data source classes and uses the
first one that is available in classpath.
1. org.apache.tomcat.jdbc.pool.DataSource
2. com.zaxxer.hikari.HikariDataSource
3. org.apache.commons.dbcp.BasicDataSource
4. org.apache.commons.dbcp2.BasicDataSource

SpringBoot by default pulls in tomcat-jdbc-{version}.jar if we add spring-boot-starter-jdbc dependency.


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

We need to exclude tomcat-jdbc from classpath If we want to use other datasources.


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>

We need to add following dependency to use HikariDataSource.


<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>

4
Real-time Approach K.RAMESH

We need to add following dependency to use commons-dbcp.


<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>

We need to add following dependency to use commons-dbcp2.


<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>

Spring Boot automatically configures above data sources based on corresponding jar file present in
classpath and connection properties should be configured in application.properties file. Various
properties can be specified inside our application.properties/application.yml file. This section provides a
list of common Spring Boot properties and references to the underlying classes that consume them.

# src/main/resources/application.properties
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=system
spring.datasource.password=manager

#tomcat-connection settings
#spring.datasource.tomcat.initialSize=20
#spring.datasource.tomcat.max-active=25

# Hikari settings
#spring.datasource.hikari.maximum-pool-size=20

# dbcp settings
#spring.datasource.dbcp.initial-size=20
#spring.datasource.dbcp.max-active=25

# dbcp2 settings
spring.datasource.dbcp2.initial-size=20
spring.datasource.dbcp2.max-total=25

If we want to use other than above datasources then we need to configure explicitly.
<dependency>
<groupId>c3p0</groupId>
5
Real-time Approach K.RAMESH

<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>

At any point we can start to define our own configuration to replace specific parts of the auto-
configuration.

#connection.properties
jdbc.driverClass=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.username=system
jdbc.password=manager
jdbc.initPoolSize=15
jdbc.maxPoolSize=25

@PropertySource(value={"classpath:connection.properties"})
public class SpringJdbcConfig {
@Autowired
private Environment env;

@Bean
public DataSource dataSource() {
ComboPooledDataSource ds = new ComboPooledDataSource();
try{
ds.setDriverClass(env.getProperty("jdbc.driverClass"));
ds.setJdbcUrl(env.getProperty("jdbc.url"));
ds.setUser(env.getProperty("jdbc.username"));
ds.setPassword(env.getProperty("jdbc.password"));
ds.setInitialPoolSize(env.getProperty("jdbc.initPoolSize", Integer.class));
ds.setMaxPoolSize(env.getProperty("jdbc.maxPoolSize", Integer.class));
}catch(Exception e){
e.printStackTrace();
}
return ds;
}
}

By default SpringBoot features such as external properties, logging, etc are available in the ApplicationContext
only if we use SpringApplication. So, SpringBoot provides @SpringApplicationConfiguration annotation to
configure the ApplicationContext for tests which uses SpringApplication behind the scenes.

6
Real-time Approach K.RAMESH

Note: As an alternate to application.properties, we can use a .yaml file. YAML provides a JSON-like structured
configuration compared to the flat properties file.
#application.yaml
Server:
port: 9080

The @SpringBootApplication enables Spring component-scanning and Spring Boot auto-configuration. In fact,
@SpringBootApplication combines three other useful annotations:
1. @SpringBootConfiguration—This annotation hints that the contained class declares one or more @Bean
definitions.

2. @ComponentScan—Enables component-scanning so that the web controller classes and other


components we write will be automatically discovered and registered as beans in the Spring application
context. This annotation is save as <context:component-scan/> element.

3. @EnableAutoConfiguration—This enables the magic of Spring Boot auto-configuration.

SPRING BOOT TEST


Spring Boot provides a number of utilities and annotations to help when testing our application. Test support is
provided by two modules; spring-boot-test contains core items, and spring-boot-test-autoconfigure supports
auto-configuration for tests.
Most developers use the spring-boot-starter-test starter which imports both Spring Boot test modules (such as
spring-boot-test and spring-boot-test-autoconfigure) as well as JUnit, AssertJ, Hamcrest, Mockito, etc.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.5.3.RELEASE</version>
</dependency>

The SpringApplication creates an appropriate ApplicationContext (depending on classpath), loads external


property files such as application.properties, enables logging and other features of spring boot. At startup,
SpringApplication loads all the properties and adds them to the Spring Environment class.

The @RunWith(SpringJUnit4ClassRunner.class) tells JUnit to run using spring’s test module.

The @ContextConfiguration(classes = .class) is used to specify which spring configuration file to load.

@SpringBootTest annotation can be used as an alternative to the standard spring-test @ContextConfiguration


annotation when we need Spring Boot features. This annotation works by creating the ApplicationContext used
in our tests via SpringApplication.
Note: Don’t forget to add @RunWith(SpringRunner.class) to our test, otherwise the annotations will be ignored.

7
Real-time Approach K.RAMESH

Spring Boot MVC


Spring Boot provides auto-configuration for Spring MVC.
If we want to keep Spring Boot MVC features then add @Configuration without @EnableWebMvc.
If we want to take complete control of Spring MVC, we can add our own @Configuration annotated with
@EnableWebMvc.

In traditional web applications, a war file is created and then deployed to a servlet container, whereas Spring
Boot packages all the dependencies to a self-contained, autonomous JAR file with an embedded HTTP listener.

Along with Spring framework there are many other Spring sister projects that help to build applications
addressing modern business needs:
Spring Data: Simplifies data access from relational and NoSQL data stores.
Spring Batch: Provides powerful batch processing framework.
Spring Security: Robust security framework to secure applications.
Spring Social: Supports integration with social networking sites like Facebook, Twitter, LinkedIn, GitHub, etc.
Spring Integration: An implementation of Enterprise Integration Patterns to facilitate integration with other
enterprise applications using lightweight messaging and declarative adapters.

You might also like