GrabObject

Spring Boot Example

Spring Boot automates the routine work that developers do while starting a project or during the development of applications. The routine work that spring boot automates includes dependent libraries addition, object decency management, configuration, embedded server setup and executable jars creation.

Spring Boot provides defaults so that you can start developing projects fast without having to manually setup or configure lots of things that you usually do while setting up a project or packaging and running applications.

Spring Boot can be used with any java IDEs with widely used build tools such as maven or gradle.

Spring Boot Example

I’ll show how to use Spring Boot taking a simple example which inserts data into and retrieves it from in-memory database. What makes developing this example easy and fast is that you don’t need to worry about adding dependencies, spring configuration and database configuration as spring boot automatically configures them.

The example uses eclipse with maven. First make sure that you have Java 1.8 or later version and install eclipse. Then create maven project.

Creating Spring Boot Project from Scratch in Eclipse

To create maven project, open eclipse, go to file menu, click new and others and then select maven project.

spring boot maven project

Follow the maven project creation wizard, select quickstart maven archetype and enter group and artifact ids and click finish.

Open the pom.xml file, and then add spring boot parent and jpa starters. For information about spring boot starters, please see Spring Boot starter tutorial.

Since we are going to use H2 in-memory database, add the dependency to it. And also, we need to add spring-boot-maven-plugin, which creates executable package jar or war, to pom.xml.

Create Spring Boot Project Using Spring Initializr

Instead of creating project from scratch and adding spring starters yourself, you can create it using spring initializr and import it to eclipse. This way you don’t need to worry about finding latest version of spring-boot-starter-parent starter and exact names of other starters.

spring boot h2 jpa initializer

POM

Here is the pom xml of our example.

<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.grabobject.spring.boot.examples</groupId>
  <artifactId>jpa-h2</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>jpa-h2</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<scope>runtime</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

Dependencies

After spring boot starters have been added to pom, you can update the project by right clicking it and selecting Maven and update project. Now you can see all the dependencies added to the project due to the spring boot starters.

spring boot h2 jpa dependencies

Spring Boot with H2 DB and JPA Example

Now let’s see how spring boot auto configuration works. This example uses H2 in-memory database and JPA to store and retrieve data. We don’t need to do anything to configure H2 database as spring boot provides default configuration. We need to just define entities and repository interfaces.

Spring boot automatically configures the application based on the jar dependencies used in the project. To enable auto configuration and inform spring about main class, we need to annotate our main class with EnableAutoConfiguration annotation. The main method should call run method of SpringApplication in order to start spring and its auto configuration features.

Entity

Create entity by annotating the class with Entity annotation and defining primary key and other column fields.

@Entity
@Table(name = "product")
public class Product {

	@Id
	@GeneratedValue
	private long id;
	private String name;
	private String brand;
	private String cat;
	private double price;

	public Product() {

	}

	public Product(Long id, String name, String brand, String cat, double price) {
		this.id = id;
		this.name = name;
		this.brand = brand;
		this.cat = cat;
		this.price = price;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getCat() {
		return cat;
	}

	public void setCat(String cat) {
		this.cat = cat;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

}

Repository

Define JpaRepository interface by extending JpaRepository interface and defining query methods. Spring generates implementation for JpaRepository interface.

@Repository
public interface ProductRepository  extends JpaRepository<Product, Long> {	
	public List<Product> findProductsByCat(String cat);	
}

Application Main

Since this is a non-web application example, the main class implements CommandLineRunner to run the application which inserts a record to database and queries the database.

@EnableAutoConfiguration
@EnableJpaRepositories
public class ProductApp implements CommandLineRunner {
	@Autowired
	private ProductRepository productRepository;
	@Autowired
	private ProductApp productApp;

	private final Logger log = LoggerFactory.getLogger(this.getClass());

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

	}

	public void products() {
		productApp.saveProducts();
		productApp.printProducts("footwear");
		productApp.printProducts("mobiles");
	}

	public void saveProducts() {
		Product p = new Product();
		p.setBrand("Nike");
		p.setCat("footwear");
		p.setName("Excellent Tennis Shoe Nike");
		p.setPrice(320.50);

		productRepository.save(p);
	}

	public void printProducts(String category) {
		List<Product> prods = productRepository.findProductsByCat(category);

		log.info("no of products in " + category + " : " + prods.size());
		for (Product p : prods) {
			log.info(p.getName());
		}
	}

	public void setProductRepository(ProductRepository productRepository) {
		this.productRepository = productRepository;
	}

	@Override
	public void run(String... args) throws Exception {
		productApp.products();
	}
}

H2 DB Default Configuration Provided By Spring Boot

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

If you want to change the configuration provided by spring boot, you can do so by adding properties to application.properties file which needs to be created under src/amin/resources folder.

Running Spring Boot Example

You can simply run the application in eclipse by clicking Run menu and Run submenu item.

running spring boot example

Creating Executable Jar

To create executable jar using spring boot, first make sure that spring-boot-maven-plugin is added to pom, then create maven run configuration with package as goal and run it. Executable jar will be created in target folder.

creating executable jar in eclipse using maven and spring boot

You can run executable jar by using java -jar your-app-SNAPSHOT.jar command.