How to Run a CommandLineRunner Bean Conditionally in Spring Boot

This article shows different ways to run a CommandLineRunner bean conditionally in a Spring Boot application. Table of contents: 1. Using @ConditionalOnProperty 2. Using Environment 3. Using Spring Profiles 4. Check the Presence of Other Beans 4.1 Using @ConditionalOnBean 4.2 Using @ConditionalOnMissingBean 5. Download Source Code 6. References P.S. Tested with Spring Boot 3.1.2 1. …

Read more

Spring Boot CommandLineRunner Example

This article tells what is CommandLineRunner and different ways of implementing it or use it in Spring Boot. Table of contents: 1. What is CommandLineRunner? 2. Implementing CommandLineRunner 3. @Bean CommandLineRunner 4. Download Source Code 5. References P.S. Tested with Spring Boot 3.1.2 1. What is CommandLineRunner? The CommandLineRunner is an interface in Spring Boot. …

Read more

Spring Boot @ServiceConnection Example

Spring Boot 3.1 introduced @ServiceConnection to enable the Spring Boot’s auto-configuration to use the service connection details to connect to a remote service (Testcontainers). Tables of contents: 1. Testing with @DynamicPropertySource 2. Spring Boot 3.1 and @ServiceConnection 3. Download Source Code 4. References 1. Testing with @DynamicPropertySource The following example uses @DynamicPropertySource to register the …

Read more

Spring Boot @DynamicPropertySource Example

In Spring Boot, we can use @DynamicPropertySource to dynamically register or override property values in the ApplicationContext for integration tests. Tables of contents: 1. Testing with ApplicationContextInitializer 2. Testing with @DynamicPropertySource 3. Testing with Spring Boot 3.1 and @ServiceConnection 4. Download Source Code 5. References P.S. The @DynamicPropertySource feature is available from Spring Framework 5.2.5 …

Read more

Spring Boot @ConditionalOnProperty Example

In Spring Boot, we can use the @ConditionalOnProperty annotation to conditionally register the beans based on the property value in the application.properties or application.yml file. This article will use the @ConditionalOnProperty annotation to simulate a toggle feature to turn features on or off at runtime without any code changes. Technologies used: Spring Boot 3.1.2 Java …

Read more

Spring Data JPA Paging and Sorting example

This article shows how to do Spring Data JPA paging and sorting using the PagingAndSortingRepository interface. Technologies used: Spring Boot 3.1.2 Spring Data JPA H2 in-memory database Java 17 Maven 3 JUnit 5 Spring Integration Tests with TestRestTemplate Unit Tests with Mocking (Mockito) Table of contents: 1. Extends PagingAndSortingRepository 2. Extends JpaRepository 3. Pageable and …

Read more

Testing Spring Data JPA with @DataJpaTest

This article shows how to use @DataJpaTest to test the Spring Data JPA application. Technologies used: Spring Boot 3.1.2 Spring Data JPA (Hibernate 6 is the default JPA implementation) H2 in-memory database Maven Java 17 JUnit 5 Table of contents: 1. Project Directory 2. Spring Data JPA – Entity and Repository 3. @DataJpaTest 3.1 Disable …

Read more

Spring Boot – package javax.persistence does not exist

We migrated the project to Spring Boot 3, and the JPA entity class hits package javax.persistence does not exist. java: package javax.persistence does not exist import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; P.S. Tested with Spring Boot 3.1.2 Solution Spring Boot 3 migrated all Java EE APIs javax.* to their equivalent Jakarta EE variant …

Read more

How to load custom properties files in Spring Boot

This article shows how to use @PropertySource annotation to load custom properties files in Spring Boot. Table of contents: 1. Load default properties file 2. Load custom properties files 3. Load multiple custom properties files 4. Download Source Code 5. References P.S. Tested with Spring Boot 3.1.2 1. Load default properties file Spring default loads …

Read more

Spring Boot Testcontainers Example

This article shows how to test the Spring Boot REST endpoints using TestRestTemplate and Testcontainers (PostgreSQL container). Technologies used : Spring Boot 3.1.2 (Spring Web MVC, Spring Data JPA and Spring Test) Testcontainers 1.19.0 PostgreSQL 15, Alpine Linux base image postgres:15-alpine Java 17 JUnt 5 Tables of contents: 1. Project Structure 2. Project Dependencies 3. …

Read more

Spring @TestPropertySource example

In Spring integration tests, we can use @TestPropertySource to override the application properties which default loaded from application.properties or application.yml. Table of contents 1. Service Class 2. Test with the @TestPropertySource 3. @TestPropertySource Inline Properties 4. Download Source Code 5. References P.S Tested with Spring Boot 3.1.2 1. Service Class 1.1 We have a service …

Read more

How to access values from application.properties in Spring Boot

In Spring Boot, we can use @Value annotation to access the values defined in the application.properties from Spring-managed beans. application.properties #Logging logging.level.org.springframework.web=ERROR logging.level.com.mkyong=DEBUG email.smtp.server=smtp.gmail.com import org.springframework.beans.factory.annotation.Value; @Value("${email.smtp.server}") private String server; Table of contents: 1. application.properties 1. @Value 2. Environment 3. @ConfigurationProperties 4. Download Source Code 5. References P.S. Tested with Spring Boot 3.1.2 1. application.properties …

Read more

package javax.validation.constraints does not exist

Below is a Spring Boot application and validation bean API example. GlobalProperties.java import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotEmpty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.validation.annotation.Validated; @Component @ConfigurationProperties @Validated public class GlobalProperties { //@Value("${thread-pool}") @Max(5) @Min(0) private int threadPool; Run the Spring Boot application and hits the following error: Terminal package javax.validation.constraints does not exist Solution – …

Read more

Spring Boot Test if web server starts on a specific port

Below is a Spring Boot Test example to test whether the web server started on port 8181. P.S. Tested with Spring Boot 3 and JUnit 5. application.properties server.port = 8181 WebServerTests.java package com.mkyong; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class WebServerTests { @LocalServerPort private int port; @Test public …

Read more

Spring Boot – Unable to find a @SpringBootConfiguration

Terminal Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test The Spring Boot tests @SpringBootTest or @DataJpaTest need to find the @SpringBootConfiguration application class to launch the entire application and do the tests. And if Spring Boot can’t find the SpringBootConfiguration, it throws errors and stops the tests. A …

Read more

Mocking Spring Data DateTimeProvider

In this article, we will demonstrate an integration test where we have to persist the entities with mocked auditing date fields when JPA Auditing is enabled. Technologies used: Spring Boot 2.4.0 Spring 5.3.1 JUnit Jupiter 5.7.0 Tomcat embed 9.0.39 Java 8 1. Project Dependencies pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> …

Read more

Spring Boot JobRunr examples

This article shows how to use Spring Boot to create REST endpoints to run the background jobs managed by the JobRunr. Tested with: Spring Boot 2.3.12.RELEASE JobRunr 3.1.2 Maven 3 1. Directory Structure. A standard Maven project structure. 2. Project Dependencies. We need a single jobrunr-spring-boot-starter to integrate Spring Boot web and JobRunr. pom.xml <!– …

Read more

Spring Boot redirect port 8080 to 8443

In Spring Boot 2.x, we can create a ServletWebServerFactory to redirect a port from HTTP 8080 to HTTPS 8443. Access localhost:8080, it will redirect to localhost:8443 1. ServletWebServerFactory For Spring Boot 2.x, try this: pom.xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> StartApplication.java package com.mkyong; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import …

Read more

Spring Boot JDBC Stored Procedure Examples

In this tutorial, we will show you how to use Spring Boot JDBC SimpleJdbcCall to call a stored procedure and stored function from a Oracle database. Technologies used : Spring Boot 2.1.2.RELEASE Spring JDBC 5.1.4.RELEASE Oracle database 19c HikariCP 3.2.0 Maven 3 Java 8 Unlike JdbcTemplate, Spring Boot didn’t create any SimpleJdbcCall automatically, we have …

Read more

Spring Boot JDBC Examples

In this tutorial, we will show you how to use Spring Boot JDBC JdbcTemplate and NamedParameterJdbcTemplate. Technologies used : Spring Boot 2.1.2.RELEASE Spring JDBC 5.1.4.RELEASE HikariCP 3.2.0 H2 in-memory database 1.4.197 Maven 3 Java 8 In Spring Boot JDBC, the database related beans like DataSource, JdbcTemplate and NamedParameterJdbcTemplate will be configured and created during the …

Read more

Spring Boot – How to send email via SMTP

In this tutorial, we will show you how to send email via SMTP in Spring Boot. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Java Mail 1.6.2 Maven 3 Java 8 1. Project Directory 2. Maven To send email, declares spring-boot-starter-mail, it will pull the JavaMail dependencies. pom.xml <?xml version="1.0" encoding="UTF-8"?> <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 …

Read more

Spring Boot Log4j 2 example

In this tutorial, we will show you how to use Apache Log4j 2 in Spring Boot framework. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Log4j 2.11.1 Maven 3 Java 8 1. Project Directory 2. Maven The key is exclude the default logback, and include log4j with spring-boot-starter-log4j2 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" …

Read more

Spring Boot + Spring Data JPA + PostgreSQL example

This article shows how to use Spring Web MVC to create REST endpoints for CRUD database operations using the Spring Data JPA and PostgreSQL. At the end of the tutorial, we will use Docker to start a PostgreSQL container to test the Spring Boot REST endpoints using curl commands. We will use Spring Test and …

Read more

Spring Boot MySQL : Table ‘DB_NAME.hibernate_sequence’ doesn’t exist

Spring Boot + Spring Data JPA + MySQL, and hits the following error message when the application starts : Tested with : Spring Boot 2.1.2.RELEASE mysql-connector-java 8.0.13 Hibernate 5.3.7 java.sql.SQLSyntaxErrorException: Table ‘DB_NAME.hibernate_sequence’ doesn’t exist at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:974) at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1024) at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52) at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java) at org.hibernate.id.enhanced.TableStructure.executeQuery(TableStructure.java:216) at org.hibernate.id.enhanced.TableStructure.access$300(TableStructure.java:46) application.properties spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=mkyong …

Read more

Spring Boot + Spring Data JPA + MySQL example

This article shows how to use Spring Web MVC to create REST endpoints to perform CRUD database operations using the Spring Data JPA and MySQL. At the end of the tutorial, we will use Docker to start a MySQL container to test the Spring Boot REST endpoints using curl commands. We will use Spring Test …

Read more

Spring Boot + Spring Data JPA example

This article shows how to use Spring Data JPA to perform CRUD operation into a H2 in-memory database. Technologies used: Spring Boot 3.1.2 Spring Data JPA (Hibernate 6 is the default JPA implementation) H2 in-memory database Maven Java 17 Table of contents: 1. Project Directory 2. Project Dependencies 3. Spring Data JPA – Entity 4. …

Read more

Spring Boot YAML example

In this article, we will show you how to use YAML instead of properties file in Spring Boot. Tested with : Spring Boot 2.1.2.RELEASE Maven 3 Snakeyaml:jar:1.23 In short, create a application.yml in the src/resources folder, Spring Boot will load and parse .yml file automatically and bind the values into the classes which annotated with …

Read more

Spring Boot – Run code when the application starts

In Spring Boot, we can create a CommandLineRunner bean to run code when the application is fully started. StartBookApplication.java package com.mkyong; 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; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; @SpringBootApplication public class StartBookApplication { public static void main(String[] args) { SpringApplication.run(StartBookApplication.class, args); } // Injects …

Read more

Spring REST Integration Test Example

In this article, we will show you how to test the Spring Boot REST application. Normally, we use the MockMvc or TestRestTemplate for the integration test. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Maven 3 Java 8 pom.xml <!– spring integration test –> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!– spring integration test for security–> …

Read more

Spring Test – How to test a JSON Array in jsonPath

In Spring, we can use Hamcrest APIs like hasItem and hasSize to test a JSON Array. Review the following example : package com.mkyong; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import …

Read more

Spring + Mockito – Unable to mock save method?

Try to mock a repository save() method, but it is always returning null? P.S Tested with Spring Boot 2 + Spring Data JPA @Test public void save_book_OK() throws Exception { Book newBook = new Book(1L, "Mockito Guide", "mkyong"); when(mockRepository.save(newBook)).thenReturn(newBook); mockMvc.perform(post("/books") .content("{json}") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()); } Solution 1. Mockito uses the equals for argument matching, try …

Read more

Spring Boot – How to init a Bean for testing?

In Spring Boot, we can create a @TestConfiguration class to initialize some beans for testing class only. P.S Tested with Spring Boot 2 1. @TestConfiguration + @Import This @TestConfiguration class will not pick up by the component scanning, we need to import it manually. TestConfig.java package com.mkyong; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import java.time.Duration; …

Read more

Mockito – How to mock repository findById thenReturn() Optional?

Try to mock a repository findById method, but no idea use thenReturn() to return an object, as it accepts an Optional? P.S Tested in Spring Boot 2 environment import static org.mockito.Mockito.*; import org.springframework.boot.test.mock.mockito.MockBean; @MockBean private BookRepository mockRepository; @Before public void init() { Book book = new Book(1L, "A Book"); //error, can’t resolve method thenReturn(book)? when(mockRepository.findById(1L)).thenReturn(book); …

Read more

Spring REST Error Handling Example

In this article, we will show you error handling in Spring Boot REST application. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Maven 3 Java 8 1. /error 1.1 By default, Spring Boot provides a BasicErrorController controller for /error mapping that handles all errors, and getErrorAttributes to produce a JSON response with details of the …

Read more

Spring REST + Spring Security Example

In this article, we will enhance the previous Spring REST Validation Example, by adding Spring Security to perform authentication and authorization for the requested URLs (REST API endpoints) Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Spring Security 5.1.3.RELEASE Spring Data JPA 2.1.4.RELEASE H2 In-memory Database 1.4.197 Tomcat Embed 9.0.14 JUnit 4.12 Maven 3 Java …

Read more

Spring Security – There is no PasswordEncoder mapped for the id “null”

Send a GET request with username and password, but hits the password encoder error? Tested Spring Boot 2.1.2.RELEASE 5.1.3.RELEASE $ curl localhost:8080/books -u user:password { "timestamp":"2019-02-22T15:03:49.322+0000", "status":500, "error":"Internal Server Error", "message":"There is no PasswordEncoder mapped for the id \"null\"", "path":"/books" } errors in logs java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" Here …

Read more