Home » Enterprise Java » spring » Spring vs Spring Boot Example

About Joel Patrick Llosa

I graduated from Silliman University in Dumaguete City with a degree in Bachelor of Science in Business Computer Application. I have contributed to many Java related projects at Neural Technologies Ltd., University of Southampton (iSolutions), Predictive Technologies, LLC., Confluence Service, North Concepts, Inc., NEC Telecom Software Philippines, Inc., and NEC Technologies Philippines, Inc. You can also find me in Upwork freelancing as a Java Developer.

Spring vs Spring Boot Example

1. Spring vs Spring Boot

Welcome to the Spring vs Spring Boot example. First and foremost, this is not Spring MVC vs Spring Boot. So you won’t find any discussion relating to web. The example that will be shown here is the simplest thing that could possibly work to show the difference between Spring and Spring Boot. When we speak of Spring in this article, we mean the Spring Core container which is at the center of all the other Spring modules. Now, on with the show.
 
 
 
 

2. Assumptions

The example here was tried and tested on a Windows 10 machine. This article assumes that the reader has a fair amount of knowledge regarding Java programming and the use of the Eclipse IDE and Apache Maven.

3. What is Spring?

The term Spring can mean different things. It can refer to the Spring Framework, where it all started. A lot of Spring projects are built on top of the Spring Framework. Most of the time when people say Spring they mean the entire family of modules (Spring Data, Spring Web, etc.). At the heart of these modules is the core container, which includes a configuration model and a dependency injection mechanism. In this example we will focus on the Spring core container.

4. Spring Example

This Spring example is Maven project. Create a Maven project in Eclipse (File -> New -> Maven Project). After creating the project, your POM should look like the one below:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javacodegeeks.example</groupId>
  <artifactId>spring-hello</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
	  <version>5.0.9.RELEASE</version>
    </dependency>
  </dependencies>

</project>

We declare spring-context as our dependency. Maven will automatically manage the dependencies so when you click on the Maven Dependencies tree in Eclipse, you should see spring-core, spring-beans, etc. included in the project.

Create the package com.javacodegeeks.example in src/main/java. Create the following files under the said package.

Main.java

package com.javacodegeeks.example;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		HiSpring hs = (HiSpring) context.getBean("hiSpring");
		hs.getMessage();
		context.close();
	}
}

HiSpring.java

package com.javacodegeeks.example;

public class HiSpring {
	private String message;

	public void setMessage(String message) {
		this.message = message;
	}

	public void getMessage() {
		System.out.println("Hi Spring message: " + message);
	}
}

Lastly, create the bean definition in src/main/java.

beans.xml

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

<beans xmlns = "http://www.springframework.org/schema/beans"
  xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation = "http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

  <bean id = "hiSpring" class = "com.javacodegeeks.example.HiSpring">
    <property name = "message" value = "Welcome to Spring!"/>
  </bean>

</beans>

5. Spring Code Walkthrough

Run (Ctrl + F11) the code above and you should have a similir output like below.

Spring Output

Sep 20, 2018 8:21:40 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@79fc0f2f: startup date [Thu Sep 20 20:21:40 BST 2018]; root of context hierarchy
Sep 20, 2018 8:21:40 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Hi Spring message: Welcome to Spring!
Sep 20, 2018 8:21:41 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@79fc0f2f: startup date [Thu Sep 20 20:21:40 BST 2018]; root of context hierarchy

ClassPathXmlApplicationContext is an implementation of the ApplicationContext interface provided by Spring out-of-the-box. ApplicationContext is a sub-interface of BeanFactory. This interface represents the Spring IoC container. The container is responsible for instantiating, configuring, and assembling the beans. In Spring, the objects that are used in your application and that are managed by a Spring IoC container are called beans. The container gets its instructions on what objects to create, configure, and assmeble by reading the configuration metadata. The configuration metadata is represented in XML, in this case beans.xml.

The getBean("hiSpring") method returns a HiSpring object with the name hiSpring. The next step is to print the the message of the bean and close the context.

Configuration metadata is traditionally supplied in an XML format but there are other ways as you will see in the Spring Boot example below. XML-based configuration metadata configure <bean/> elements inside a top-level <beans/>. The bean definitions correspond to objects that make up the application. The id attribute is a string used to identify the individual bean definition. The class attribute uses the fully qualified class name that defines the type of the bean. The beans.xml follows the setter-based dependency injection format. Setter-based DI is accomplished by calling the setter method of the bean after invoking a no-argument constructor. So this means the property element equates to setMessage("Welcome to Spring!").

6. What is Spring Boot?

Spring Boot is not a framework. Spring Boot makes it easy to create stand-alone Spring-based applications that you can run. Most Spring Boot applications require very little Spring configuration. In a way, it is bootstrapping the way you create your application by setting up the libraries your project needs, setting up minimal configurations depending on the jars on the classpath, etc. It basically wants to provide a fast and accessible getting-started experience for all Spring development. In short, Spring Boot is a tool or way to create Spring-based applications.

7. Spring Boot Example

This Spring Boot example is Maven project. Create a Maven project in Eclipse (File -> New -> Maven Project). After creating the project, your POM should look like the one below:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javacodegeeks.example</groupId>
  <artifactId>spring--boot-hello</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
	  <version>1.5.15.RELEASE</version>
    </dependency>
  </dependencies>

</project>

We declare spring-boot-starter as our dependency. Maven will automatically manage the dependencies so when you click on the Maven Dependencies tree in Eclipse, you should see spring-boot, spring-boot-autoconfigure, spring-core, spring-beans, etc. included in the project.

Create the package com.javacodegeeks.example in src/main/java. Create the following files under the said package.

Main.java

package com.javacodegeeks.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Main implements CommandLineRunner {

	@Autowired
	ApplicationContext context;

	public static void main(String[] args) {
		SpringApplication.run(Main.class, args);

	}

	public void run(String... args) throws Exception {
		HiSpringBoot hs = (HiSpringBoot) context.getBean("hiSpringBoot");
		hs.getMessage();
	}

	@Bean
	public HiSpringBoot hiSpringBoot() {
		HiSpringBoot hsb = new HiSpringBoot();
		hsb.setMessage("Welcome to Spring Boot!");

		return hsb;
	}

}

HiSpringBoot.java

package com.javacodegeeks.example;

public class HiSpringBoot {
	private String message;

	public void setMessage(String message) {
		this.message = message;
	}

	public void getMessage() {
		System.out.println("Hi Spring Boot message: " + message);
	}

}

8. Spring Boot Code Walkthrough

Run (Ctrl + F11) the code above and you should have a similir output like below.

Spring Boot Output

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.15.RELEASE)

2018-09-20 20:17:06.845  INFO 13484 --- [           main] com.javacodegeeks.example.Main           : Starting Main on xxxxxxxxxx with PID 13484 (D:\xxxxxxxxxx\workspace\spring-boot-hello\target\classes started by jpllosa in D:\xxxxxxxxxx\workspace\spring-boot-hello)
2018-09-20 20:17:06.861  INFO 13484 --- [           main] com.javacodegeeks.example.Main           : No active profile set, falling back to default profiles: default
2018-09-20 20:17:06.892  INFO 13484 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@fcd6521: startup date [Thu Sep 20 20:17:06 BST 2018]; root of context hierarchy
2018-09-20 20:17:07.298  INFO 13484 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
Hi Spring Boot message: Welcome to Spring Boot!
2018-09-20 20:17:07.316  INFO 13484 --- [           main] com.javacodegeeks.example.Main           : Started Main in 0.705 seconds (JVM running for 1.18)
2018-09-20 20:17:07.316  INFO 13484 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@fcd6521: startup date [Thu Sep 20 20:17:06 BST 2018]; root of context hierarchy
2018-09-20 20:17:07.316  INFO 13484 --- [       Thread-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

Instead of annotating our class with @Configuration, @EnableAutoConfiguration, and @ComponentScan, we use the @SpringBootApplication annotation as a convenient alternative. This annotation tells Spring Boot to scan for other components, add beans based on the classpath, and tags the class as a source of bean definitions. We implemented the CommandLineRunner because we want to execute the run method after the application context is loaded. @Autowired automatically injects an ApplicationContext object. The SpringApplication class bootstraps a Spring application that is started from a main() method.

@Bean is a method-level annotation. We are able to use this annotation because our class is @Configuration (@SpringBootApplication). The hiSpringBoot() method registers a bean definition within an ApplicationContext of the type HiSpringBoot. By default, the bean name is the same as the method name. This declaration makes a bean available named hiSpringBoot in the ApplicationContext, bound to an object of type HiSpringBoot.

The bean naming convention is to use the standard Java convention for instance field names. So bean names start with a lowercase letter and are camel-cased from then on. Hence, we have hiSpringBoot. Naming beans consistently makes the configuration easy to read and understand.

9. Spring vs Spring Boot Code Comparison

First and the most glaring difference is that there is no XML configuration in Spring Boot. Spring Boot auto-configured the application context. A SpringApplication attempts to create the right type of ApplicationContext on your behalf. The Main.class was delegated to SpringApplication.run which shows logging information including relevant startup details. Another advantage with Spring Boot is the compiler can check our code whereas if we have a lot of XML configuration and were missing a letter or something, that would be hell to debug.

10. Spring vs Spring Boot Summary

There you have it. Two ways of displaying ‘hello world’ in spring. Which would you prefer? Java-based configuration or XML? In spring boot, a lot is preconfigured for us depending on the jars we include. It makes building a Spring-based application a bit easier. But we still need to learn about XML configuration, who knows, you might be assigned to maintain an old Spring application with lots of XML configuration. Yay!

11. Download the Source Code

This is an example about Spring vs Spring Boot.

Download
You can download the source code of this example here: spring-vs-spring-boot-example.zip.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Daniel Tremblay
Daniel Tremblay
2 years ago

Could you tell us what the start-up time for each application was? Is there a difference in memory consumption?