1. What is Spring Framework & Spring Boot?
Spring Framework is a Java framework that provides infrastructure support for building enterprise-level applications. Its biggest feature is Inversion of Control (IoC): instead of you creating and wiring objects yourself (
new SomeClass()
), Spring creates and manages objects (beans) for you, injecting them where needed.-
Spring Boot is a tool built on top of Spring Framework that makes development much faster by:
- Auto-configuring things (no XML configs anymore).
- Providing “starter” dependencies (just add one line in
pom.xml
instead of 10). - Embedding Tomcat/Jetty so you can run apps with just
java -jar
.
Without Spring Boot, you’d need to manually configure database connections, servlet containers, and beans. With Spring Boot, it’s mostly automatic.
2. Spring Core
- IoC Container: A box that creates and manages your objects (beans).
- ApplicationContext: The main Spring container that loads bean definitions and wires dependencies.
- Bean Lifecycle: How beans are created, initialized, and destroyed.
Example:
@Configuration
public class AppConfig {
@Bean
public MessageService messageService() {
return new MessageService();
}
}
public class MessageService {
public String getMessage() {
return "Hello, Spring!";
}
}
public class Main {
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
MessageService service = context.getBean(MessageService.class);
System.out.println(service.getMessage());
}
}
Explanation:
-
@Configuration
tells Spring this class defines beans. -
@Bean
registers a bean (MessageService
) inside the container. -
ApplicationContext
loads the beans and manages them. - Instead of
new MessageService()
, we ask Spring for it (getBean
).
Bean Scopes:
- singleton (default) → one instance for the whole app.
- prototype → new instance each time you ask for it.
- request → one per HTTP request (web apps only).
- session → one per user session.
3. Interceptors & Filters
- Filters (Servlet level): Work before a request even reaches Spring. Good for logging, authentication, etc.
- Interceptors (Spring MVC level): Work before/after controllers. Good for cross-cutting concerns like measuring execution time.
Example: Filter
@Component
public class LoggingFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
System.out.println("Request received at: " + new Date());
chain.doFilter(req, res);
}
}
Explanation: Every request goes through this filter. It logs the time, then continues (chain.doFilter
).
Example: Interceptor
@Component
public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
System.out.println("Before Controller: " + req.getRequestURI());
return true; // continue request
}
}
Explanation: Before Spring MVC calls your controller method, this interceptor runs. You can stop the request by returning false
.
4. Properties / YAML Files
Spring Boot uses application.properties
or application.yml
for configuration.
application.properties
server.port=8081
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
Explanation:
-
server.port=8081
→ runs your app on port 8081. -
spring.datasource.url=...
→ configures database connection.
Spring Boot reads this automatically — no manual parsing required.
5. Dependencies
Example pom.xml
:
<dependencies>
<!-- Web Starter (REST APIs, Tomcat embedded) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA + H2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
Explanation:
-
spring-boot-starter-web
gives you Spring MVC + Tomcat. -
spring-boot-starter-data-jpa
gives you Hibernate + JPA. -
h2
gives you an in-memory database (great for testing). -
spring-boot-starter-security
adds authentication & authorization.
6. H2 Database Configuration
application.properties
:
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
Explanation:
-
spring.h2.console.enabled=true
lets you open a web-based DB viewer. - Visit
http://localhost:8080/h2-console
to see your in-memory DB.
7. Build a Todo REST API
Entity
@Entity
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private boolean completed;
}
Explanation:
-
@Entity
maps this class to a DB table. -
@Id
marks the primary key. -
@GeneratedValue
lets DB auto-generate IDs.
Repository
public interface TodoRepository extends JpaRepository<Todo, Long> { }
Explanation:
-
JpaRepository
already provides methods likesave()
,findAll()
,deleteById()
. - No need to write SQL manually.
Controller
@RestController
@RequestMapping("/api/todos")
public class TodoController {
@Autowired
private TodoRepository repo;
@GetMapping
public List<Todo> getAll() {
return repo.findAll();
}
@PostMapping
public Todo create(@RequestBody Todo todo) {
return repo.save(todo);
}
@PutMapping("/{id}")
public Todo update(@PathVariable Long id, @RequestBody Todo todo) {
todo.setId(id);
return repo.save(todo);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
repo.deleteById(id);
}
}
Explanation:
-
@RestController
→ class returns JSON. -
@RequestMapping("/api/todos")
→ all endpoints start with/api/todos
. -
@GetMapping
→ returns all todos. -
@PostMapping
→ creates a todo (data comes from request body). -
@PutMapping
→ updates a todo. -
@DeleteMapping
→ deletes a todo by ID.
8. Basic Auth Security
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/**").authenticated()
.anyRequest().permitAll()
)
.httpBasic();
return http.build();
}
@Bean
public UserDetailsService users() {
UserDetails user = User.builder()
.username("admin")
.password("{noop}password") // {noop} = plain text
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
Explanation:
-
csrf().disable()
disables CSRF protection (simplifies APIs). -
.httpBasic()
enables HTTP Basic Auth → browsers prompt for username/password. -
InMemoryUserDetailsManager
defines a test user (admin/password
). - Now,
GET /api/todos
requires authentication.
Top comments (0)