Spring – Latest Validated Notes

Spring Framework 7.0.9 reference-aligned • Core • DI • Component Scanning • AOP • Transactions • JDBC • MVC • REST

Contents

  1. Spring Core & IoC
  2. Dependency Injection
  3. Component Scanning
  4. Java Configuration & XML
  5. Bean Lifecycle & Scopes
  6. Spring AOP
  7. Transactions
  8. JdbcTemplate
  9. Spring MVC / REST
  10. Interview Revision

1. Spring Core & IoC

Spring's IoC container creates, configures and assembles application objects called beans. Dependency Injection is the common way to express those dependencies.

BeanFactory
Core IoC container API and a lower-level foundation.
ApplicationContext
Higher-level container commonly used in application development.

Program – Basic Bean

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();
        }
    }
}
Modern recommendation: Prefer Java configuration and component scanning for new applications. XML remains useful for legacy systems and for understanding older Spring projects.

2. Dependency Injection

Constructor Injection – Recommended for Required Dependencies

@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();
    }
}

Why Constructor Injection?

3. Component Scanning

@Component@Service@Repository@Controller

Component scanning detects eligible stereotype-annotated classes and registers them as Spring beans.

Program – Component Scanning

@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();
        }
    }
}
Important: The screenshot issue has been fixed in this HTML: code text uses a dedicated high-contrast code style, so programs are clearly visible against the dark code panel.

4. Java Configuration and XML Configuration

Java Configuration – Modern Style

@Configuration
class AppConfig {
    @Bean
    public PaymentService paymentService() {
        return new PaymentService();
    }
}

XML – Legacy / Interview Knowledge

<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>

5. Bean Lifecycle and Scopes

ScopeMeaning
singletonOne bean instance per Spring container; default scope.
prototypeA new instance is created when requested from the container.
requestOne bean instance per HTTP request in a web-aware context.
sessionOne bean instance per HTTP session in a web-aware context.

Program – Initialization and Destruction

@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");
    }
}

6. Spring AOP

AOP modularizes cross-cutting concerns such as logging, security and transaction management.

TermMeaning
AspectModule containing cross-cutting behavior.
Join pointA point during execution where advice can conceptually apply.
PointcutExpression selecting join points.
AdviceAction taken at selected join points.
ProxyObject through which Spring commonly applies AOP advice.

Program – Logging Aspect

@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());
        }
    }
}

7. Spring Transactions

Spring declarative transaction management is commonly implemented through AOP interception and a transaction manager.

Program – Service Transaction

@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);
    }
}
PropagationMeaning
REQUIREDJoin existing transaction or create one.
REQUIRES_NEWSuspend current transaction and start a new one.
SUPPORTSJoin if present; otherwise execute non-transactionally.
MANDATORYExisting transaction required.
NOT_SUPPORTEDSuspend transaction and execute without one.
NEVERFail if a transaction exists.
NESTEDNested/savepoint semantics where supported.

8. JdbcTemplate CRUD

Program – Insert, Query and Update

@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);
    }
}

9. Spring MVC / REST

Request Flow

Client
  ↓
DispatcherServlet
  ↓
HandlerMapping
  ↓
Controller
  ↓
Service
  ↓
Repository / Database
  ↓
HTTP Response

Program – REST Controller

@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);
    }
}

10. Spring Interview Quick Revision

QuestionAnswer
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.