Diff of Spring and Spring boot | |
---|---|
1) Spring Framework is a widely used Java EE framework for building applications. | 1)Spring Boot Framework is widely used to develop REST APIs. |
2)It aims to simplify Java EE development that makes developers more productive. | 2)It aims to shorten the code length and provide the easiest way to develop Web Applications. |
3)The primary feature of the Spring Framework is dependency injection. | 3)The primary feature of Spring Boot is Autoconfiguration. It automatically configures the classes based on the requirement. |
4)It helps to make things simpler by allowing us to develop loosely coupled applications. | 4)It helps to create a stand-alone application with less configuration. |
5)To test the Spring project, we need to set up the sever explicitly. | 5)Spring Boot offers embedded server such as Jetty and Tomcat, etc. |
6)Developers manually define dependencies for the Spring project in pom.xml. | 6)Spring Boot comes with the concept of starter in pom.xml file that internally takes care of downloading the dependencies JARs based on Spring Boot Requirement. |
Q.1) What is spring boot and its main features?
Ans) Spring boot has been built on top of existing spring framework which provides 4 main features:
I. Starters to minimize number of dependencies in pom.xml file
II. Autoconfiguration to reduce spring configuration file size
III. Embedded server to avoid external server
IV. Actuators to get insight about Spring boot project such as total list of beans, dependency details, autoconfig report, health, environment, metrics, etc
Q.2) How to write Hello World program by using Spring Boot?
Ans)
@RestController
@SpringBootApplication
public class Example { //bootstrap class
@RequestMapping("/")
public String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
Q.3) What is Spring Boot Initializer?
Ans) It is a web tool which is provided by Spring on official site. We can create Spring Boot project by providing project details. Select Maven project and dependencies. Fill other details and click on generate project.
Q.4) How to disable Actuator endpoint security in Spring Boot?
Ans)
The property:
management.security.enabled=false was valid in Spring Boot 1.x but was removed in Spring Boot 2.x and above, including Spring Boot 3.x.
Correct Way in Spring Boot 3.x (Spring Security 6)
To disable security for Actuator endpoints, you should do it via Spring Security configuration.
Option 1: Permit all Actuator endpoints
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import static org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest.toAnyEndpoint;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(toAnyEndpoint()).permitAll() // allow all actuator endpoints
.anyRequest().authenticated()
)
.httpBasic(withDefaults()); // or formLogin, etc.
return http.build();
}
}
Option 2: Permit specific Actuator endpoints
.requestMatchers(EndpointRequest.to("health", "info")).permitAll()
Also Consider:
In application.properties, you may want to expose the desired endpoints:
management.endpoints.web.exposure.include=*
Q.5) How to implement security in a Spring Boot 3 application?
I. Add Spring Security dependency in pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
II. You DO NOT need @EnableWebSecurity anymore unless customizing SecurityFilterChain manually.❌
From Spring Boot 2.7+ and 3.x, @EnableWebSecurity is not required unless you're doing manual security configuration.
Preferred Approach (Spring Boot auto-configuration):
Just create a configuration class with a SecurityFilterChain bean.
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
III. management.security.enabled=true — ❌ INVALID
That property is removed in Spring Boot 2.x+.
Use SecurityFilterChain config to secure management (Actuator) endpoints explicitly.
If you're using Actuator, also configure:
management.endpoints.web.exposure.include=*
IV. security.user.name — ❌ Invalid key (was valid in Boot 1.x)
Use these instead in Spring Boot 3:
properties
spring.security.user.name=aspire
spring.security.user.password=aspire123
Final Correct Properties for Spring Boot 3.x
properties
spring.security.user.name=aspire
spring.security.user.password=aspire123
Summary
Step Original Valid in Spring Boot 3? Correction
I Add starter dependency ✅ Yes No change
II Use @EnableWebSecurity ❌ Not required Use SecurityFilterChain bean instead
III management.security.enabled ❌ Removed Use explicit config in SecurityFilterChain
IV security.user.name/password ❌ Invalid keys Use spring.security.user.name/password instead
Q.6) How to integrate Spring Boot and RabbitMQ? (Spring Boot 3.x)
i) Add dependency in pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
ii) Define the queue in a configuration class
You should register the queue as a Spring Bean (not just return it randomly).
@Configuration
public class RabbitMQConfig {
@Bean
public Queue searchQueue() {
return new Queue("SearchQ", false); // durable = false
}
}
iii) Send and receive messages using RabbitTemplate and @RabbitListener
Producer (sending message):
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendMessage(Map<String, Object> map) {
rabbitTemplate.convertAndSend("SearchQ", map);
}
Consumer (receiving message):
@RabbitListener(queues = "SearchQ")
public void receiveMessage(Map<String, Object> message) {
System.out.println("Received: " + message);
}
Also make sure @EnableRabbit is added in a configuration class or main class to enable listener detection:
@SpringBootApplication
@EnableRabbit
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Q.7) What is Swagger
Swagger is a set of open-source tools for documenting and testing RESTful APIs. It allows developers and consumers to understand and interact with the API without needing access to the source code.
In Spring Boot, Swagger is typically integrated via the OpenAPI 3.0 specification using the library called springdoc-openapi.
Q.8) How to implement Swagger (OpenAPI) in Spring Boot 3.x
i) Add dependency in pom.xml:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.3.0</version> <!-- Or latest -->
</dependency>
ii) Access Swagger UI:
By default, Swagger UI will be available at:
http://localhost:8080/swagger-ui.html
iii) Add OpenAPI metadata (optional):
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.info.Info;
@OpenAPIDefinition(
info = @Info(title = "My API", version = "1.0", description = "Spring Boot API Documentation")
)
@SpringBootApplication
public class Application { ... }
Q.9) How to run Spring boot application to custom port ?
Ans) Add server.port=9090 in application.properties file.
8. How to check whether a Spring Boot application is running?
There are two levels to check the application’s status:
1) System Level Monitoring (OS/Deployment Level)
You can run your Spring Boot application as a systemd service (Linux), Docker container, or Kubernetes pod.
Linux Systemd Example:
sudo systemctl status myapp
Docker container:
docker ps
docker inspect <container_id>
Kubernetes:
kubectl get pods
kubectl get deployment myapp
This tells you if the process is alive, but not if the application is healthy.
2) Application-Level Monitoring (using Actuator + Micrometer)
You should include the Spring Boot Actuator dependency and optionally Micrometer for metrics.
Dependencies (pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId> <!-- or Datadog, NewRelic, etc -->
</dependency>
⚙️ application.properties Configuration:
# Expose specific endpoints
management.endpoints.web.exposure.include=health,info,metrics,prometheus
# Optional: Change actuator base path
management.endpoints.web.base-path=/actuator
Common Endpoints:
GET /actuator/health → Check if app is healthy (UP/DOWN).
GET /actuator/info → Show app info if configured.
GET /actuator/metrics → Micrometer-based metrics.
GET /actuator/prometheus → Prometheus-formatted metrics (if enabled).
Example Health Check JSON:
{
"status": "UP",
"components": {
"db": { "status": "UP" },
"diskSpace": { "status": "UP" },
"ping": { "status": "UP" }
}
}
BONUS: Custom Health Indicators
You can write your own HealthIndicator to contribute to /actuator/health.
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// custom logic here
return Health.up().withDetail("customService", "Available").build();
}
}
Summary
There are two approaches:
1. System Level
Use tools like systemctl, docker ps, or kubectl to verify if the application process or container is running.
2. Application Level
Use Spring Boot Actuator with endpoints like:
/actuator/health → Health status
/actuator/info → App info
/actuator/metrics → App metrics
/actuator/prometheus → Prometheus exporter
These endpoints expose runtime state and health via HTTP or JMX.
To enable metrics, integrate with Micrometer and use backends like Prometheus, Datadog, etc.
Q.10) What is @ConditionalOnClass annotation?
@ConditionalOnClass
is a Spring Boot conditional annotation that enables configuration only if a specific class is present on the classpath.
It is used to conditionally enable a @Configuration
class or a @Bean
definition, depending on whether the specified class or classes are available in the application’s classpath.
Q.11) What is
@Conditional
in Spring?@Conditional
is a core Spring Framework annotation that lets you define custom conditions for when a bean or configuration should be created.
It is a meta-annotation used to build conditional logic in the Spring container.
Q.12) How to integrate Spring with Hibernate using Spring Boot?
Ans)
i) Add the Spring Data JPA starter dependency in your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
ii) (No need to explicitly add @EnableAutoConfiguration in most cases) because:
The @SpringBootApplication annotation already includes @EnableAutoConfiguration, which automatically configures Hibernate and other JPA-related beans based on the dependencies present.
This means Spring Boot will automatically configure Hibernate as the JPA provider when spring-boot-starter-data-jpa is included.
iii) Configure your database connection properties in application.properties or application.yml, for example:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=pass
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
iv) Define your entity classes annotated with @Entity and repositories extending JpaRepository or CrudRepository.
Q13.) How to customize spring boot actuator?
Provides built-in endpoints to monitor and manage your application (e.g., /actuator/health, /actuator/metrics).
You can expose, secure, and customize these endpoints.
You can also create your own custom actuator endpoints.
How to Customize Actuator?
1. Enable/Disable Endpoints
In application.properties or application.yml, control which endpoints are exposed:
management.endpoints.web.exposure.include=health,info,mycustom
management.endpoints.web.exposure.exclude=shutdown
2. Add Custom Endpoint
You can create your own actuator endpoint by implementing @Endpoint or @RestController (for HTTP endpoints):
Example: Custom Health Endpoint
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;
@Component
@Endpoint(id = "mycustom")
public class MyCustomEndpoint {
@ReadOperation
public String customInfo() {
return "This is my custom actuator endpoint!";
}
}
This will expose /actuator/mycustom endpoint.
3. Customizing Existing Endpoints
You can add info to the /actuator/info endpoint via application.properties:
management.info.app.name=MyApp
management.info.app.version=1.0.0
Or programmatically via InfoContributor:
import org.springframework.boot.actuate.info.Info;
import org.springframework.boot.actuate.info.InfoContributor;
import org.springframework.stereotype.Component;
@Component
public class MyInfoContributor implements InfoContributor {
@Override
public void contribute(Info.Builder builder) {
builder.withDetail("app", Map.of("name", "MyApp", "version", "1.0.0"));
}
}
4. Secure Actuator Endpoints
Use Spring Security to restrict access:
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
In your security config, whitelist or secure /actuator/** endpoints as needed.
Summary:
Task How to do it
Enable/disable endpoints management.endpoints.web.exposure.include
Add custom endpoint Create class with @Endpoint and @ReadOperation
Add custom info Use InfoContributor or properties
Secure endpoints Spring Security configuration
Q.14) What is @SpringBootApplication annotation in Spring Application class?
Ans)
The @SpringBootApplication internally same as 3 annotations such as
@SpringBootConfiguration,
@EnableAutoConfiguration and
@ComponentScan.
Also @SpringBootApplication annotation makes class as a bootstrap class.
The SpringApplication class automatically creates context based on type of configuration file.
Q.15) How to use Jetty instead of Tomcat with spring boot?
Ans:
By default, Spring Boot uses Tomcat as the embedded servlet container. To use Jetty instead, you need to:
Exclude the default Tomcat starter dependency.
Add the Jetty starter dependency.
Example pom.xml changes:
<!-- Exclude Tomcat from spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Add Jetty starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Explanation:
The spring-boot-starter-web includes Tomcat by default.
Excluding spring-boot-starter-tomcat prevents Tomcat from being on the classpath.
Adding spring-boot-starter-jetty adds Jetty as the embedded server instead.
Q.16) How to use Netty instead of Tomcat with Spring Boot?
Ans:
Spring Boot supports Netty as the embedded web server, but only when using Spring WebFlux (the reactive web framework). You cannot replace Tomcat with Netty in Spring MVC (spring-boot-starter-web) because Netty is a non-servlet, reactive server.
Steps to use Netty in Spring Boot:
Use Spring Boot Starter WebFlux instead of Starter Web.
Add the spring-boot-starter-webflux dependency (which uses Netty by default).
Remove spring-boot-starter-web and spring-boot-starter-tomcat dependencies if present.
Example pom.xml dependencies:
<!-- Remove spring-boot-starter-web -->
<!-- Add spring-boot-starter-webflux which includes Netty -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
Explanation:
spring-boot-starter-webflux uses Netty as the default embedded server.
It supports reactive programming and is designed for non-blocking applications.
If you want traditional blocking servlet-based applications, you need Tomcat, Jetty, or Undertow.
Summary:
Scenario Server
Spring MVC (blocking) Tomcat (default), Jetty, Undertow
Spring WebFlux (reactive) Netty (default), also supports Jetty, Undertow
Q.17) How to reflect code changes without restarting boot application?
i) Add spring-boot-devtools dependency in pom.xml file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
ii) Spring-loaded
iii) JRebel
Comments
Post a Comment