Skip to main content

Spring Boot

 Spring Boot

  • Automatic configuration—Spring Boot can automatically provide configuration for application functionality common to many Spring applications.
  • Starter dependencies—You tell Spring Boot what kind of functionality you need, and it will ensure that the libraries needed are added to the build. 
  • The command-line interface—This optional feature of Spring Boot lets you write complete applications with just application code, but no need for a traditional project build.
  • The Actuator—Gives you insight into what’s going on inside of a running Spring Boot application.

@SpringBootApplication combines three other useful annotations:

  • Spring’s @Configuration—Designates a class as a configuration class using Spring’s Java-based configuration.
  • ■ Spring’s @ComponentScan—Enables component-scanning so that the web controller classes and other components you write will be automatically discovered and registered as beans in the Spring application context.
  • ■ Spring Boot’s @EnableAutoConfiguration—This humble little annotation might as well be named @Abracadabra because it’s the one line of configuration that enables the magic of Spring Boot auto-configuration. This one line keeps you from having to write the pages of configuration that would be required otherwise.

H : 

  • SpringBoot test class can be annotated with @SpringApplicationConfiguration(classes = ReadingListApplication.class) this will load the spring boot context.
@Test
public void contextLoads() {}
can be used to make sure context is loaded successfully.

CONFIGURING APPLICATION PROPERTIES

Change port : server.port=8000

Using starter dependencies
org.springframework.boot:spring-boot-starter-web
org.springframework.boot:spring-boot-starter-thymeleaf
org.springframework.boot:spring-boot-starter-data-jpa

H :

mvn dependency:tree

Overriding starter transitive dependencies

Exclusion
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
        </exclusion>
    </exclusions>
</dependency>

Version Override 
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>

Using automatic 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. To illustrate, here are a few examples of the kinds of things that Spring Boot auto-configuration might consider:
  • Is Spring’s JdbcTemplate available on the classpath? If so and if there is a Data- Source bean, then auto-configure a JdbcTemplate bean.
  • Is Thymeleaf on the classpath? If so, then configure a Thymeleaf template resolver, view resolver, and template engine.
  • Is Spring Security on the classpath? If so, then configure a very basic web security setup.
  • There are nearly 200 such decisions that Spring Boot makes with regard to autoconfiguration every time an application starts up,

Externalizing configuration with properties

This list is in order of precedence.
  1. Command-line arguments
  2. JNDI attributes from java:comp/env
  3. JVM system properties
  4. Operating system environment variables
  5. Randomly generated values for properties prefixed with random.* (referenced when setting other properties, such as `${random.long})
  6. An application.properties or application.yml file outside of the application
  7. An application.properties or application.yml file packaged inside of the application
  8. Property sources specified by @PropertySource
  9. Default properties

As for the application.properties and application.yml files, they can reside in any
of four locations:
  1. Externally, in a /config subdirectory of the directory from which the application is run
  2. Externally, in the directory from which the application is run
  3. Internally, in a package named “config

CONFIGURING THE EMBEDDED SERVER

server.port=8000
java -jar readinglist-0.0.1-SNAPSHOT.jar --server.port=8000

server.port=8443
server.ssl.key-store= file:///path/to/mykeys.jks
server.ssl.key-store-password: letmein
server.ssl.key-password: letmein

CONFIGURING A DATA SOURCE

Spring Boot will use this connection data when auto-configuring the DataSource bean. The DataSource bean will be pooled, using Tomcat’s pooling DataSource if it’s available on the classpath. If not, it will look for and use one of these other connection pool implementations on the classpath:
  • HikariCP
  • Commons DBCP
  • Commons DBCP 2

Externally configuring application beans


@Configuration @ConfigurationProperties(prefix = "mail") public class ConfigProperties { private String hostName; private int port; private String from; // standard getters and setters }

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

application.properties

mail.hostname=host@mail.com mail.port=9000 mail.from=mailer@mail.com

N :

Spring uses some relaxed rules for binding properties. As a result, the following variations are all bound to the property hostName:
  • mail.hostName
  • mail.hostname
  • mail.host_name
  • mail.host-name
  • mail.HOST_NAME

Configuring with profiles


@Profile("production")
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

}

java -jar readinglist-0.0.1-SNAPSHOT.jar --spring.profiles.active=production

pring.profiles.active= production

creating additional properties files named withthe pattern “application-{profile}.properties”.

Testing with Spring Boot


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AddressBookConfiguration.class)
public class AddressServiceTests {

@Autowired
private AddressService addressService;

@Test
public void testService() {
Address address = addressService.findByLastName("Sheman");
assertEquals("P", address.getFirstName());
assertEquals("Sherman", address.getLastName());
assertEquals("42 Wallaby Way", address.getAddressLine1());
assertEquals("Sydney", address.getCity());
assertEquals("New South Wales", address.getState());
assertEquals("2000", address.getPostCode());
}
}

@RunWith is given SpringJUnit4ClassRunner.class to enable Spring integration testing.

@ContextConfiguration specifies how to load the application context. Here we’re asking it to load the Spring application context given the specification defined in AddressBookConfiguration.

SpringJUnit4ClassRunner also makes it possible to inject beans from the application context into the test itself via autowiring. Because this test is targeting an AddressService bean, it is autowired into the test.

Testing web applications

  1. Spring Mock MVC—Enables controllers to be tested in a mocked approximation of a servlet container without actually starting an application server
  2. Web integration tests—Actually starts the application in an embedded servlet container (such as Tomcat or Jetty), enabling tests that exercise the application in a real application server

Mocking Spring MVC

@SpringBootTest(classes = DroneApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
class DroneApplicationTests {

@Autowired
private WebApplicationContext webContext;
private MockMvc mockMvc;

@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webContext).build();
}

@Test
void contextLoads() {
}
@Test
void getAllDrones() {
   try {
mockMvc.perform(MockMvcRequestBuilders.get("api/drones/getListOfAvailableDrones"))
.andExpect(MockMvcResultMatchers.status().isOk());
   } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
  }
}
}

Testing web security


<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

@Before
public void setupMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(webContext).apply(springSecurity()).build();
}

With Spring Security enabled, we can no longer simply request the home page and expect an HTTP 200 response. If the request isn’t authenticated, we should expect a redirect to the login page:

@Test
public void homePage_unauthenticatedUser() throws Exception {
mockMvc.perform(get("/")).andExpect(status().is3xxRedirection())
.andExpect(header().string("Location", "http://localhost/login"));
}

But how can we perform an authenticated request? Spring Security offers two annotations that can help:
  • @WithMockUser—Loads the security context with a UserDetails using the given username, password, and authorization
  • @WithUserDetails—Loads the security context by looking up a UserDetails object for the given username

The @WithMockUser annotation is the most basic of the two. It allows you to explicitly declare a UserDetails to be loaded into the security context:

@Test
@WithMockUser(username="craig", password="password", roles="READER")
public void homePage_authenticatedUser() throws Exception {

}

The @WithUserDetails annotation uses the configured UserDetailsService to load the UserDetails object.

Testing a Running Application 

By annotating a test class with @WebIntegrationTest, you declare that you want Spring Boot to
not only create an application context for your test, but also to start an embedded servlet container. Once the application is running along with the embedded container, you can issue real HTTP requests against it and make assertions against the results.

Running Server in random port 

@WebIntegrationTest(value={"server.port=0"})
Or
@WebIntegrationTest("server.port=0")
@WebIntegrationTest(randomPort=true)



Comments

Popular posts from this blog

Spring Boot 4 Ready

Spring Boot 4.x Features Explained:  Java 25, AI Agents, MCP, Resilience, gRPC & Cloud Native Evolution Building on the massive architectural shift introduced in version 3, Spring Boot 4.x bridges the gap between traditional enterprise stability and the rapid demands of modern cloud architecture and AI integration. While Spring Boot 3 introduced the foundations for GraalVM Native Images and Virtual Threads , Spring Boot 4 takes these capabilities mainstream, introduces native resilience patterns, and upgrades the underlying Spring ecosystem. Spring Boot 4 Major Theme: Modern enterprise development with cloud-native architecture, AI integration, improved resilience, better modularity, and optimized JVM performance. Table of Contents 1. Upgraded Foundation & Baselines 2. Built-in Core Resilience Features 3. First-Class Agentic AI & Model Context Protocol (MCP) 4. Native API Versioning Strategy 5. Modern...

Most questions in 2025

Java Spring Boot Senior Engineer Interview Questions & Answers A complete interview preparation guide for Senior Java Engineers, Spring Boot Developers, and Backend Technical Leads covering Java, Spring Boot, Microservices, Cloud, Database, Security, and Performance Engineering concepts. Target Audience: Senior Java Developers Spring Boot Engineers Microservice Architects Backend Technical Leads Table of Contents 1. Describe Yourself 2. RESTful APIs and Standards 3. Latest Spring Boot Version & Features 4. Java Optional 5. WebFlux Reactive Programming 6. WebFlux Retry Mechanism 7. WebFlux Pagination APIs 8. Circuit Breaker 9. Resilience Patterns 10. Rate Limiter 1. Describe Yourself A senior engineer introduction should highlight technical experience, architecture knowledge, ownership, and problem-solving capabilities. Sample Answer I am a Java backend engineer with 7+ years of experience desi...

Data Structure

Java Data Structures A highly-scannable architectural cheat sheet for developers and technical interviews. 1. Linear vs. Non-Linear: The Core Division Data Structure Classification Hierarchy ┌───────────────────────┐ │ Data Structures │ └───────────┬───────────┘ │ ┌───────────────┴───────────────┐ ▼ ▼ ┌────────────────────┐ ┌────────────────────┐ │ Linear (Seq) │ │ Non-Linear │ └──────────┬─────────┘ └──────────┬─────────┘ │ │ ┌──────┴──────┐ ┌──────┴──────┐ ▼ ▼ ▼ ▼ [Static] [Dynamic] [Trees] [Graphs] (Array) (Queue, Stack) (BST) (Network) ...