How to configure H2 Database in Spring Boot

Usually, we configure the H2 database in the web.xml file as a Servlet, but Spring Boot is using an embedded instance of Tomcat, so we don’t have access to the web.xml file. Spring Boot does provide us a mechanism to use for declaring servlets via a Spring Boot ServletRegistrationBean.

The following Spring Configuration declares the Servlet wrapper for the H2 database console and maps it to the path of /h2Console.

@Configuration
public class WebConfiguration {
	@Bean
	ServletRegistrationBean h2servletRegistration() {
		ServletRegistrationBean registrationBean = new ServletRegistrationBean(new WebServlet());
		registrationBean.addUrlMappings("/h2Console/*");
		return registrationBean;
	}
}
Advertisements

SOLID Principles

The SOLID principles were first conceptualized by Robert C. Martin and later built upon by Michael Feathers, who introduced us to “SOLID” acronym. As per their study, design principles encourage us to create more maintainable, understandable, and flexible software. Therefore, as our applications grow in size, we can reduce it’s complexity and better management.

Following are the SOLID principles for each developer/architect reference:-

  • Single Responsibility:- This principle states that a class should have only one responsibility and one reason to change. Once acheived, following are the benefits for the same:-
    • Testing – A class with one responsibility will have fewer test cases
    • Loose Coupling – Less functionality in a single class will have fewer dependencies
    • Organized – Smaller, well-organized classes are easier to search than monolithic ones
  • Open/Closed:- Following principle states that classes should be open for extension, but closed for modification. In doing so, we stop ourselves from modifying existing code and causing potential new bugs. By extending the Parent class we can be sure that our existing application won’t be affected.
  • Liskov Substitution:- Functions that use references to base classes must be able to use objects of the derived class without knowing it. In simple words, derived classes must be substitutable for the base class. It’s recommended to call public parent methods to get your results in the sub-classes and not directly using the internal variables. That way you are making sure the parent abstractions get to the required state without side effects or invalid state transitions. It’s also recommended keeping your base Abstractions as simple and minimal as possible, making it easy to extend by the sub-classes.
  • Interface Segregation:- Larger interfaces should be split into smaller ones. By doing so, we can ensure that implementing classes only need to be concerned about the methods that are of interest to them.
  • Dependency Inversion:- The principle of Dependency Inversion refers to the decoupling of software modules. This way, instead of high-level modules depending on low-level modules, both will depend on abstractions.

How Spring and Spring Boot Bootstraps Works?

Spring supports both the legacy web.xml way of bootstrapping as well as the latest Servlet 3+ method.

  • Approach using web.xml
    • Servlet container reads web.xml file and DispatcherServlet defined in the web.xml is instantiated by the container
    • DispatcherServlet creates WebApplicationContext by reading WEB-INF/{servletName}-servlet.xml
    • Finally, DispatcherServlet registers the beans defined in the application context
  • Approach using Servlet 3+
    • Container searches for classes implementing ServletContainerInitializer and executes
    • SpringServletContainerInitializer finds all classes implementing WebApplicationInitializer
    • WebApplicationInitializer creates the context with XML or @Configuration classes and further creates DispatcherServlet

Spring Boot uses an embedded servlet container to run an application using a class which is annotated with @SpringBootApplication. In this case, Spring Boot uses the public static void main entry-point to launch an embedded web server which takes care of binding of the Servlet, Filter and ServletContextInitializer beans from the application context.

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Spring Boot also provides the option of deploying it as a web archive in an external container and for this we have to extend the SpringBootServletInitializer. Here, the external servlet container looks for the Main-class defined in the META-INF file of web archive and the SpringBootServletInitializer will take care of binding the Servlet, Filter, and ServletContextInitializer.

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    ...
    ...
}

Happy Learning !!

What is Spring and Spring Boot?

Spring provides Dependency Injection and out of the box modules which can drastically reduce the development time of an application. Few of the modules are given below:-

    • Spring MVC
    • Spring JDBC
    • Spring Security
    • Spring AOP
    • Spring ORM

Spring Boot is an extension of Spring framework which eliminates the boilerplate configurations required for setting up a Spring application. Few of the features in Spring Boot are given below:-

    • Starter dependencies for fast development
    • Automatic configurations to simplify build and deployment
    • Embedded server to avoid complexity in application deployment
    • Metrics, Health check and externalized configurations

Caching @ Spring Boot

Caching is becoming an integral part of all applications to enhance the speed of providing data. It helps in reducing the roundtrip calls to Database, REST Service, File, etc. Spring provides a Cache Abstraction, which enables integrating caching providers (EhCache, Hazelcast, Infinispan, Couchbase, Redis, etc.) with the existing Spring application. It is materialized by the org.springframework.cache package through Cache and CacheManager interfaces.

Let’s have a cross-check for annotation based caching with Spring Boot:-

@EnableCaching:- It enables Spring’s annotation-driven cache management capability. In spring boot project, we need to add it to the boot application class annotated with @SpringBootApplication. Spring provides one concurrent hashmap as default cache, but we can override CacheManager to register external cache providers as well easily.

@Cacheable:- It is used on the method level to let spring know that the response of the method are cacheable. Spring manages the request/response of this method to the cache specified in annotation attribute. For example, @Cacheable(“cacheFirstKeyName”, “cacheSecondKeyName”).

@CachePut:- Sometimes we need to manipulate the cacheing manually to update cache before method call. This will allow us to update the cache and will also allow the method to be executed. The method will always be executed and its result placed into the cache.

@CacheEvict:- It is used when we need to evict (remove) the cache previously loaded of master data. When CacheEvict annotated methods will be executed, it will clear the cache.

@Caching:- It regroups multiple cache operations to be applied to a method. For example, we could have both CachePut and CacheEvict at the same time.

@Transactional Annotation and it’s Attributes

We can fine tune the @Transactional annotation by changing the setting of the attributes.

  • propagation — Optional setting for propagation. This is a very important attribute in setting the transactional behavior.
    • REQUIRED — support a current transaction, create a new one if none exist
    • REQUIRES_NEW — create a new transaction and suspend the current transaction if none exist
    • MANDATORY — support a current transaction, throw an exception if none exists
    • NESTED — executes within a nested transaction if a current transaction exists
    • SUPPORTS — supports currents transaction but execute non-transactionally if none exists
  • isolation — Transaction isolation level. It decides the level to what the transaction should be isolated to other transactions
    • DEFAULT — default isolation level of the datasource
    • READ_COMMITTED — indicates dirty reads to be prevented, non-repeatable, and phantom reads can occur
    • READ_UNCOMMITTED — indicates that dirty reads, non-repeatable, and phantom reads can occur
    • REPEATABLE_READ — indicates dirty and non-repeatable reads are prevented but phantom reads can occur
    • SERIALIZABLE — indicates dirty read phantom read, and non-repeatable reads are prevented
  • readOnly — whether the transaction is read-only or read/write
  • timeout — transaction timeout
  • rollbackFor — arrays of exception class objects that must cause a rollback of the transaction
  • rollbackForClassName — arrays of exception class names that must cause a rollback of the transaction
  • noRollbackFor — arrays of exception class objects that must not cause a rollback of the transaction
  • noRollbackForClassName — arrays of exception class names that must not cause a rollback of the transaction

Actuator @ Spring Boot

Spring Boot provides the Spring Boot Actuator module for monitoring and managing your application when it is moved into production. Some of the production-ready features it provides are health monitoring of the application, auditing of the events, and gathering of metrics from the production environments.

For enabling the Spring Boot actuator, we need to add the following Spring Boot starter Maven dependency in pom.xml.

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

Spring Boot actuator provides the /info endpoint (http://localhost:8080/actuator/info) to display the information about the application. This is useful if you want to learn more about the version, name, and some other basic properties of the application.

The application level metrics are exposed via the /metrics actuator endpoint. This is useful if you want to the know the OS and JVM information of the application running in an environement. The information is as follows when we hit the application at localhost:8080/actuator/metrics

If we want to look for a specific metric from the above result, actuator provides the information. For example, if want to see the JVM heap memory used, we can check at the endpoint http://localhost:8080/actuator/metrics/jvm.memory.used.