Spring Framework 7.0.9 reference-aligned • Core • DI • Component Scanning • AOP • Transactions • JDBC • MVC • REST
Spring's IoC container creates, configures and assembles application objects called beans. Dependency Injection is the common way to express those dependencies.
public class OrderService {
public void placeOrder() {
System.out.println("Order placed");
}
}
@Configuration
class AppConfig {
@Bean
OrderService orderService() {
return new OrderService();
}
}
public class Main {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class)) {
OrderService service = ctx.getBean(OrderService.class);
service.placeOrder();
}
}
}
@Repository
class OrderRepository {
public void save() {
System.out.println("Saved order");
}
}
@Service
class OrderService {
private final OrderRepository repository;
public OrderService(OrderRepository repository) {
this.repository = repository;
}
public void create() {
repository.save();
}
}
@Component@Service@Repository@Controller
Component scanning detects eligible stereotype-annotated classes and registers them as Spring beans.
@Service
public class OrderService {
public void process() {
System.out.println("Processing order");
}
}
@Configuration
@ComponentScan("com.example")
class AppConfig {
}
public class Main {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext(AppConfig.class)) {
ctx.getBean(OrderService.class).process();
}
}
}
@Configuration
class AppConfig {
@Bean
public PaymentService paymentService() {
return new PaymentService();
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="orderService"
class="com.example.OrderService"/>
</beans>
| Scope | Meaning |
|---|---|
| singleton | One bean instance per Spring container; default scope. |
| prototype | A new instance is created when requested from the container. |
| request | One bean instance per HTTP request in a web-aware context. |
| session | One bean instance per HTTP session in a web-aware context. |
@Component
public class ReportService {
@PostConstruct
public void init() {
System.out.println("Bean initialized");
}
public void generate() {
System.out.println("Generating report");
}
@PreDestroy
public void destroy() {
System.out.println("Bean destroyed");
}
}
AOP modularizes cross-cutting concerns such as logging, security and transaction management.
| Term | Meaning |
|---|---|
| Aspect | Module containing cross-cutting behavior. |
| Join point | A point during execution where advice can conceptually apply. |
| Pointcut | Expression selecting join points. |
| Advice | Action taken at selected join points. |
| Proxy | Object through which Spring commonly applies AOP advice. |
@Aspect
@Component
public class LoggingAspect {
@Around("execution(* com.example.service..*(..))")
public Object log(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("START: " + pjp.getSignature());
try {
return pjp.proceed();
} finally {
System.out.println("END: " + pjp.getSignature());
}
}
}
Spring declarative transaction management is commonly implemented through AOP interception and a transaction manager.
@Service
public class TransferService {
private final AccountRepository repository;
public TransferService(AccountRepository repository) {
this.repository = repository;
}
@Transactional
public void transfer(Long from, Long to, BigDecimal amount) {
repository.debit(from, amount);
repository.credit(to, amount);
}
}
| Propagation | Meaning |
|---|---|
| REQUIRED | Join existing transaction or create one. |
| REQUIRES_NEW | Suspend current transaction and start a new one. |
| SUPPORTS | Join if present; otherwise execute non-transactionally. |
| MANDATORY | Existing transaction required. |
| NOT_SUPPORTED | Suspend transaction and execute without one. |
| NEVER | Fail if a transaction exists. |
| NESTED | Nested/savepoint semantics where supported. |
@Repository
public class EmployeeDao {
private final JdbcTemplate jdbc;
public EmployeeDao(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public int insert(Employee e) {
return jdbc.update(
"insert into employee(name, salary) values (?, ?)",
e.getName(), e.getSalary());
}
public List<Employee> findAll() {
return jdbc.query(
"select id, name, salary from employee",
(rs, rowNum) -> new Employee(
rs.getLong("id"),
rs.getString("name"),
rs.getBigDecimal("salary")));
}
public int updateSalary(long id, BigDecimal salary) {
return jdbc.update(
"update employee set salary=? where id=?",
salary, id);
}
}
Client
↓
DispatcherServlet
↓
HandlerMapping
↓
Controller
↓
Service
↓
Repository / Database
↓
HTTP Response
@RestController
@RequestMapping("/api/orders")
public class OrderController {
private final OrderService service;
public OrderController(OrderService service) {
this.service = service;
}
@GetMapping("/{id}")
public OrderDto get(@PathVariable Long id) {
return service.findById(id);
}
@PostMapping
public ResponseEntity<OrderDto> create(
@RequestBody CreateOrderRequest request) {
OrderDto saved = service.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(saved);
}
}
| Question | Answer |
|---|---|
| IoC? | Control of object creation and dependency wiring is delegated to the container. |
| DI? | Dependencies are supplied to an object rather than the object constructing them itself. |
| Default bean scope? | Singleton. |
| BeanFactory vs ApplicationContext? | BeanFactory is the core IoC contract; ApplicationContext is the richer application-level container. |
| Why constructor injection? | Explicit required dependencies, immutability and testability. |
| What does @Transactional use internally? | Spring transaction interception with AOP proxies and a transaction manager in the common proxy-based model. |
| What is self-invocation? | A direct call within the same object that bypasses the Spring proxy. |