Scrolling through endless Javatpoint pages to learn Spring? This guide consolidates the entire Javatpoint Spring tutorial into one structured, actionable learning path for 2026. Whether you're wrestling with the inversion of control container for the first time or trying to wrap your head around microservices, I've organized everything you need—core concepts, MVC, Boot, data access, security, and interview prep—into a single, coherent journey. No more juggling fifteen browser tabs.
I've been building enterprise Java applications for over fifteen years, and I've trained dozens of junior developers who came to me overwhelmed by Spring's sheer size. The problem isn't that Spring is hard—it's that most tutorials throw everything at you at once. This guide fixes that by sequencing the material the way I wish someone had taught me.
Spring Framework Core Concepts: IoC, DI, and Bean Lifecycle
Let's start where every spring framework javatpoint tutorial begins: the foundation. If you don't understand the core container, everything else—MVC, Boot, Security—will feel like magic you can't debug.
What is Inversion of Control (IoC) and Dependency Injection?
Here's the simplest way I can put it: Inversion of Control means you stop creating your dependencies and start receiving them. Instead of a new keyword inside your class, you declare what you need and let the container hand it to you.
The inversion of control container is Spring's core engine. It manages your objects (called "beans") and wires them together. Think of it as a matchmaking service—your classes don't go out looking for partners; they just say "I need a UserRepository" and the container makes the introduction.
Let me show you what this looks like in practice. Here's constructor-based injection:
public class UserService {
private final UserRepository userRepository;
// Spring will automatically provide the UserRepository instance
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
And here's setter-based injection:
public class EmailService {
private MailSender mailSender;
@Autowired
public void setMailSender(MailSender mailSender) {
this.mailSender = mailSender;
}
}
I personally prefer constructor injection for required dependencies—it makes testing easier and prevents partially-initialized objects. Setter injection works better for optional dependencies.
The contrast with the old EJB approach is stark. Before Spring, enterprise Java meant heavyweight EJBs with complex deployment descriptors, remote interfaces, and a container that dictated your architecture. Spring flipped that model: plain old Java objects (POJOs) with annotations, no mandatory interfaces, and a lightweight container that stays out of your way.
Spring Bean Scopes: Singleton, Prototype, and More
One question I get constantly from beginners: "Why is my bean holding state from another request?" The answer usually comes down to scope.
| Scope | Description | Use Case |
|---|---|---|
| singleton (default) | One instance per Spring container | Stateless services, repositories |
| prototype | New instance every time it's requested | Stateful beans, complex objects |
| request | One instance per HTTP request | Request-scoped data holders |
| session | One instance per HTTP session | User session data |
| application | One instance per ServletContext | Application-wide shared state |
| websocket | One instance per WebSocket | WebSocket session data |
The default scope is singleton, which trips up a lot of people. In most cases, that's exactly what you want—your UserService doesn't need multiple instances. But if you're holding mutable state, prototype scope is your friend. |
Here's how you'd define scope in XML:
<bean id="shoppingCart" class="com.example.ShoppingCart" scope="prototype"/>
And with annotations:
@Component
@Scope("prototype")
public class ShoppingCart {
// stateful bean
}
Spring Bean Lifecycle Methods Explained
Every bean in the Spring container goes through a predictable lifecycle: instantiation, property population, initialization, and eventually destruction. Understanding this sequence matters because it determines where you hook in custom logic.
Here's a practical example:
@Component
public class DatabaseConnection {
@PostConstruct
public void init() {
System.out.println("Opening database connection pool...");
// initialize connection pool
}
@PreDestroy
public void cleanup() {
System.out.println("Closing database connection pool...");
// release resources
}
}
You can also use XML configuration:
<bean id="databaseConnection" class="com.example.DatabaseConnection"
init-method="init" destroy-method="cleanup"/>
In my experience, @PostConstruct and @PreDestroy are the cleanest approach for modern Spring applications. They're part of the Java EE standard (jakarta.annotation), so they work across frameworks, not just Spring.
One thing I've learned the hard way: don't do heavy work in @PostConstruct if you can avoid it. It runs synchronously during startup, and slow initialization there will delay your entire application boot.
Spring MVC and REST API Development: A Practical Guide
Now we're getting into the part that actually builds things users interact with. The spring mvc javatpoint material covers a lot of ground, but the core pattern is consistent.
Understanding the DispatcherServlet and Request Flow
Every Spring MVC request flows through a single entry point: the DispatcherServlet. It's the front controller that receives all HTTP requests and delegates to the appropriate handlers.
Here's the flow I walk through with every developer I mentor:
- The browser sends a request to
/products/42 DispatcherServletreceives it and consults theHandlerMappingto find which controller method handles this URL- The controller method executes, returning a logical view name or a response body
- If it's a view, the
ViewResolvermaps the logical name to an actual JSP or Thymeleaf template - The response goes back through
DispatcherServletto the client
A minimal Java-based configuration looks like this:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.controller")
public class WebConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
Building a REST API with Spring MVC
For REST APIs, you'll use @RestController instead of @Controller. The difference? @RestController combines @Controller and @ResponseBody, meaning the return value goes directly into the HTTP response body as JSON (or XML, depending on content negotiation).
Here's a complete REST controller for a Product entity:
@RestController
@RequestMapping("/api/products")
public class ProductController {
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@GetMapping
public List<Product> getAllProducts() {
return productService.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
return productService.findById(id)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Product createProduct(@RequestBody Product product) {
return productService.save(product);
}
@PutMapping("/{id}")
public Product updateProduct(@PathVariable Long id, @RequestBody Product product) {
product.setId(id);
return productService.save(product);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteProduct(@PathVariable Long id) {
productService.deleteById(id);
}
}
Notice how I'm using ResponseEntity for fine-grained control over HTTP status codes. For the GET /{id} endpoint, returning 404 when the product doesn't exist is the right call—and ResponseEntity makes that explicit.
Exception Handling in Spring MVC
Raw stack traces in JSON responses are a surefire way to frustrate your API consumers. Spring gives you a clean way to centralize exception handling.
Here's a @ControllerAdvice class that handles exceptions globally:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleResourceNotFound(ResourceNotFoundException ex) {
return new ErrorResponse("NOT_FOUND", ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleValidationErrors(MethodArgumentNotValidException ex) {
String message = ex.getBindingResult().getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.collect(Collectors.joining(", "));
return new ErrorResponse("VALIDATION_ERROR", message);
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleGenericException(Exception ex) {
// Log the exception here
return new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred");
}
}
The @ExceptionHandler annotation binds a specific exception type to a handler method. @ControllerAdvice makes those handlers available across all controllers. This pattern has saved me countless hours of debugging—all error responses follow the same structure, and I can add new exception types without touching individual controllers.
Spring Boot vs Spring Framework: Which One Should You Choose in 2026?
This is the javatpoint spring vs spring boot difference question that comes up in every training session I run. The short answer: for new projects in 2026, choose Spring Boot. But understanding why requires looking at what each brings to the table.
Key Differences: Auto-Configuration, Opinionated Defaults, and Embedded Server
| Feature | Spring Framework | Spring Boot |
|---|---|---|
| Configuration | Manual XML or Java config | Auto-configuration with sensible defaults |
| Server | External (Tomcat, Jetty, etc.) | Embedded server (Tomcat by default) |
| Setup time | Significant—you configure everything | Minutes with Spring Initializr |
| Dependency management | Manual version management | Starter POMs handle versions |
| Production readiness | You build it yourself | Actuator, health checks, metrics out of the box |
| Learning curve | Steeper—you need to understand internals | Gentler—start coding quickly |
| Spring Boot doesn't replace Spring—it builds on top of it. You're still using the same core container, the same MVC framework, the same data access abstractions. Boot just removes the friction of configuration. |
I've seen teams spend days setting up a Spring MVC project with XML configuration, only to have Spring Boot generate the equivalent in seconds. The trade-off is that Boot's "magic" can obscure what's happening under the hood. That's why I recommend learning core Spring concepts first, even if you'll ultimately build with Boot.
Migration Path: From Spring to Spring Boot
If you have a legacy Spring application, migrating to Boot doesn't have to be a rewrite. Here's the step-by-step approach I've used successfully:
- Create a new Spring Boot project with the same dependencies as your existing app
- Copy over your Java source files—controllers, services, repositories, entities
- Replace XML configuration with annotations—
@Configuration,@ComponentScan,@EnableWebMvc - Move properties to
application.propertiesorapplication.yml - Replace web.xml with a
WebApplicationInitializeror rely on Boot's auto-configuration - Test incrementally—start with one module, verify it works, then move to the next
The biggest challenge I've encountered is dealing with custom configuration that Boot's auto-configuration doesn't cover. In those cases, you can exclude specific auto-configurations:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Spring Boot Deep Dive: Auto-Configuration and Microservices
The javatpoint spring boot material really shines when you get into auto-configuration. This is where Boot earns its keep.
How Spring Boot Auto-Configuration Works
The @SpringBootApplication annotation is actually three annotations combined:
@SpringBootConfiguration—marks this as a configuration class@EnableAutoConfiguration—turns on auto-configuration@ComponentScan—scans for components in the current package and sub-packages
Auto-configuration works by examining your classpath. If you have H2 on the classpath, Boot configures an in-memory database. If you have spring-boot-starter-web, Boot configures an embedded Tomcat server and Spring MVC. It's conditional—Boot checks what's available and configures accordingly.
Here's how you override a default auto-configured bean:
@Configuration
public class CustomDataSourceConfig {
@Bean
@Primary
public DataSource dataSource() {
HikariDataSource dataSource = new HikariDataSource();
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUsername("admin");
dataSource.setPassword("secret");
return dataSource;
}
}
The @Primary annotation tells Spring to prefer this bean when multiple candidates exist.
Building Microservices with Spring Boot and Spring Cloud
Microservices are where Spring Boot really flexes its muscles. The combination of Boot and Spring Cloud gives you service discovery, centralized configuration, and API gateways.
Here's a simple microservice that registers itself with Eureka:
@SpringBootApplication
@EnableEurekaClient
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
}
And in application.yml:
spring:
application:
name: product-service
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
The @EnableEurekaClient annotation tells Spring Cloud to register this service with the Eureka server. Other services can then discover it by name instead of hardcoding IP addresses.
I'll be honest: microservices add significant operational complexity. For small teams or simple applications, a well-structured monolith is often the better choice. But if you're dealing with independent scaling requirements or multiple teams owning different domains, the microservice pattern pays off.
Spring Boot Actuator: Monitoring Your Application
Actuator gives you production-ready monitoring endpoints out of the box. The most useful ones:
/actuator/health—application health status/actuator/metrics—JVM, memory, and HTTP metrics/actuator/info—custom application information/actuator/env—environment properties
Here's what a health check response looks like:
{
"status": "UP",
"components": {
"db": {
"status": "UP",
"details": {
"database": "MySQL",
"validationQuery": "isValid()"
}
},
"diskSpace": {
"status": "UP",
"details": {
"total": 499963170816,
"free": 234567890123,
"threshold": 10485760
}
}
}
}
By default, only /health and /info are exposed. To enable more endpoints:
management:
endpoints:
web:
exposure:
include: health,info,metrics,env
And you should secure these endpoints—they reveal sensitive information about your application. Spring Security can restrict them to authenticated users or specific IP addresses.
Spring Data JPA and Transaction Management: Database Integration
Database access is where many javatpoint spring data jpa crud example searches originate. Let me walk you through a complete example.
Spring Data JPA CRUD Example with MySQL
First, add the dependencies to your pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
Configure your datasource:
spring:
datasource:
url: jdbc:mysql://localhost:3306/userdb
username: root
password: password
jpa:
hibernate:
ddl-auto: update
show-sql: true
Create an entity:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String name;
// constructors, getters, setters
}
Create a repository interface:
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
List<User> findByNameContaining(String keyword);
}
And a REST controller:
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserRepository userRepository;
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found with id: " + id));
user.setEmail(userDetails.getEmail());
user.setName(userDetails.getName());
return userRepository.save(user);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
}
}
The beauty of Spring Data JPA is that you don't write any implementation for the repository. Spring generates it at runtime based on the method names. findByEmail becomes a query automatically.
Spring Transaction Management: @Transactional Best Practices
Transactions ensure data consistency—either all operations in a unit of work succeed, or none of them do. Spring's @Transactional annotation makes this declarative.
Here's a service-layer example:
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final InventoryService inventoryService;
public OrderService(OrderRepository orderRepository, InventoryService inventoryService) {
this.orderRepository = orderRepository;
this.inventoryService = inventoryService;
}
@Transactional
public Order placeOrder(OrderRequest request) {
Order order = new Order();
order.setCustomerId(request.getCustomerId());
order.setItems(request.getItems());
order.setStatus("PLACED");
Order savedOrder = orderRepository.save(order);
// This will throw an exception if inventory is insufficient
inventoryService.deductStock(request.getItems());
return savedOrder;
}
}
If deductStock throws an exception, the entire transaction rolls back—the order won't be saved. That's the behavior you want.
Key attributes of @Transactional:
- propagation—defines how transactions relate to each other (REQUIRED, REQUIRES_NEW, etc.)
- isolation—defines how transaction changes are visible to other transactions
- rollbackFor—specifies which exceptions trigger rollback
One pitfall I've seen repeatedly: @Transactional doesn't work when you call a method from within the same class. Spring uses proxies, and self-invocation bypasses the proxy. If you need self-invocation to be transactional, you'll need to use TransactionTemplate or restructure your code.
Spring Security and AOP: Securing and Modularizing Your Application
Security isn't optional in 2026. The javatpoint spring security authentication example is one of the most searched topics in the Spring ecosystem, and for good reason.
Spring Security Authentication and Authorization Example
Here's a security configuration class for a Spring Boot application:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.requestMatchers("/api/users/**").hasAnyRole("USER", "ADMIN")
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("admin")
.password(passwordEncoder().encode("admin123"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
This gives you in-memory authentication with role-based access control. For production, you'd typically use JDBC or OAuth2 authentication, but the pattern is the same.
I strongly recommend using BCrypt for password hashing. It's computationally expensive by design, which makes brute-force attacks impractical. Never store plain-text passwords—I've seen the aftermath of that mistake in production systems, and it's not pretty.
Spring AOP Tutorial with Aspect-Oriented Programming
AOP lets you separate cross-cutting concerns—logging, security, transactions—from your business logic. Instead of sprinkling logging code throughout every method, you define an aspect that intercepts method calls.
Here's a logging aspect:
@Aspect
@Component
public class LoggingAspect {
private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
@Around("execution(* com.example.service.*.*(..))")
public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getSimpleName();
long startTime = System.currentTimeMillis();
logger.info("Executing {}.{}()", className, methodName);
try {
Object result = joinPoint.proceed();
long duration = System.currentTimeMillis() - startTime;
logger.info("Completed {}.{}() in {} ms", className, methodName, duration);
return result;
} catch (Exception e) {
logger.error("Exception in {}.{}(): {}", className, methodName, e.getMessage());
throw e;
}
}
}
The @Around annotation means this advice wraps the method execution. The execution expression defines which methods to intercept—in this case, all methods in the com.example.service package.
AOP is powerful, but it can also make code harder to debug. When you see a method doing something it doesn't appear to do, an aspect is probably involved. Use it judiciously—logging, security checks, and transaction management are the sweet spots.
Javatpoint Spring Interview Questions: The Ultimate Prep Guide
After fifteen years of conducting technical interviews, I've seen the same javatpoint spring interview questions come up again and again. Here's what you actually need to know.
Top 20 Core Spring Interview Questions and Answers
1. What is Spring Framework? Spring is a lightweight, open-source framework for building enterprise Java applications. It provides comprehensive infrastructure support, with IoC and DI at its core.
2. What is Inversion of Control? IoC is a principle where the control of object creation and lifecycle is transferred from the application to the container. Instead of creating dependencies yourself, you declare them and the container provides them.
3. What is Dependency Injection? DI is a design pattern where dependencies are provided to a class rather than created by it. Spring supports constructor-based, setter-based, and field-based injection.
4. What are the different bean scopes in Spring? Singleton (default), prototype, request, session, application, and websocket.
5. What is the default bean scope? Singleton—one instance per Spring container.
6. What is the difference between BeanFactory and ApplicationContext?
BeanFactory is the basic IoC container with lazy initialization. ApplicationContext extends it with eager initialization, AOP support, internationalization, and event publishing.
7. What is Spring AOP? Aspect-Oriented Programming in Spring allows separation of cross-cutting concerns like logging and security from business logic.
8. What is the difference between @Component, @Service, and @Repository?
They're all stereotype annotations for component scanning. @Service and @Repository are specializations of @Component that add semantic meaning—@Repository also enables exception translation for database exceptions.
9. What is @Autowired? It's an annotation that tells Spring to inject a dependency automatically. It can be used on constructors, setters, and fields.
10. What is the difference between @Controller and @RestController?
@RestController combines @Controller and @ResponseBody, meaning return values go directly into the HTTP response body.
11. What is DispatcherServlet? It's the front controller in Spring MVC that handles all HTTP requests and delegates to appropriate handlers.
12. What is @RequestMapping? It maps HTTP requests to handler methods. It can specify URL, HTTP method, parameters, and headers.
13. What is the difference between @RequestParam and @PathVariable?
@RequestParam extracts query parameters (/api/users?role=admin), while @PathVariable extracts values from the URL path (/api/users/42).
14. What is Spring Boot auto-configuration? It's Boot's mechanism to automatically configure beans based on classpath dependencies and properties, reducing manual configuration.
15. What is @SpringBootApplication?
It combines @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan.
16. What is Spring Data JPA? It's a repository abstraction that reduces boilerplate code for data access. You define interfaces, and Spring generates implementations.
17. What is @Transactional? It's an annotation that manages transactions declaratively. It can be applied to methods or classes.
18. What is Spring Security? It's a framework for authentication and authorization in Java applications.
19. What is Spring Cloud? It's a set of tools for building distributed systems—service discovery, configuration management, API gateways, and more.
20. What is the difference between Spring and Spring Boot? Spring is the core framework with IoC, DI, MVC, and AOP. Spring Boot builds on Spring to simplify setup, configuration, and deployment with auto-configuration and embedded servers.
Spring Boot and Microservices Interview Questions
1. How does Spring Boot auto-configuration work?
It examines the classpath for dependencies and conditionally configures beans based on what's present. The @EnableAutoConfiguration annotation triggers this process.
2. What is Spring Boot Actuator? It provides production-ready endpoints for monitoring and managing your application—health checks, metrics, environment properties, and more.
3. What is service discovery in microservices? It's a pattern where services register themselves with a registry (like Eureka) and discover other services by name rather than hardcoded addresses.
4. What is an API gateway? It's a single entry point for all client requests, handling routing, authentication, rate limiting, and other cross-cutting concerns.
5. What is distributed tracing? It's a technique to track requests as they flow through multiple microservices, using correlation IDs to correlate logs across services.
6. What is the difference between Eureka and Consul? Both are service discovery tools. Eureka is Netflix's implementation, while Consul also provides key-value storage and multi-datacenter support.
7. What is Spring Cloud Config Server? It's a centralized configuration service that manages configuration properties for multiple microservices.
8. What is circuit breaker pattern? It's a pattern that prevents cascading failures by failing fast when a downstream service is unavailable, rather than waiting for timeouts.
9. What is the difference between @FeignClient and RestTemplate?
@FeignClient is a declarative REST client—you define an interface and Feign generates the implementation. RestTemplate is a more manual approach.
10. How do you handle distributed transactions in microservices? The saga pattern is the common approach—a sequence of local transactions with compensating actions for rollback.
Frequently Asked Questions
What is the difference between Spring and Spring Boot?
| Aspect | Spring | Spring Boot |
|---|---|---|
| Configuration | Manual XML/Java config | Auto-configuration |
| Server | External server required | Embedded server included |
| Setup | Complex, time-consuming | Quick with Spring Initializr |
| Production features | Build yourself | Actuator included |
| Spring Boot is built on top of Spring. It doesn't replace the core framework—it simplifies using it. For new projects in 2026, Spring Boot is almost always the right choice. |
How to create a Spring MVC project in Javatpoint?
The Javatpoint-style approach involves these steps:
- Create a Maven project with the Spring MVC dependencies
- Configure
DispatcherServletinweb.xmlor with aWebApplicationInitializer - Create a controller class with
@Controllerand@RequestMapping - Configure a
ViewResolverto map logical view names to JSP files - Deploy to an external Tomcat server
With Spring Boot, you'd use Spring Initializr, add spring-boot-starter-web, and you're ready to code in minutes.
What is the default scope of a Spring bean?
The default scope is singleton. This means Spring creates one instance of the bean per container, and all requests for that bean return the same instance. This is ideal for stateless beans like services and repositories. To change it, use @Scope("prototype") or the scope attribute in XML configuration.
How to handle exceptions in Spring MVC?
Use @ExceptionHandler within a controller for local exception handling, or @ControllerAdvice for global handling. The @ControllerAdvice approach centralizes exception logic and returns consistent error responses. You can combine it with @ResponseStatus to set appropriate HTTP status codes.
Conclusion
This learning path has taken you from Spring's core concepts—IoC, DI, bean lifecycle—through MVC and REST APIs, into Spring Boot and microservices, and finally to data access, security, and interview preparation. That's the complete javatpoint spring tutorial journey, consolidated into one guide.
The key to mastering Spring is hands-on practice. Reading about dependency injection is one thing; debugging a circular dependency at 2 AM is another. Build something small first—a simple REST API with Spring Boot—then expand into data access, security, and eventually microservices.
I've seen developers go from "what's a bean?" to building production-grade microservices in six months of consistent practice. The framework rewards patience and curiosity.
Start building your first Spring Boot application today! Download our free project template and follow along with the examples. If you have questions, leave a comment below or join our community forum.

