Mastering Spring: Core Concepts, Modules, Annotations & Advanced Features

This comprehensive guide walks through Spring’s fundamentals—including IoC, DI, core modules, common annotations, AOP concepts, transaction management, MVC workflow, and Spring Boot auto‑configuration—while also covering advanced topics such as bean lifecycle, circular dependencies, proxy mechanisms, and an introduction to Spring Cloud.

Sanyou's Java Diary
Sanyou's Java Diary
Sanyou's Java Diary
Mastering Spring: Core Concepts, Modules, Annotations & Advanced Features

Basics

Spring is a lightweight, non‑intrusive framework that provides Inversion of Control (IoC) and Aspect‑Oriented Programming (AOP) for Java applications. It was created in 2003 by Rod Johnson and quickly replaced heavyweight EJBs.

1. What is Spring? What are its features?

IoC and DI support

AOP programming

Declarative transaction management

Annotation‑driven configuration

Integration with many third‑party frameworks (Struts, Hibernate, MyBatis, Quartz, etc.)

Template APIs (JdbcTemplate, RestTemplate)

Test support with JUnit

2. Core Spring modules

Spring Core – provides IoC and DI

Spring Context – advanced BeanFactory

Spring Web – web support

Spring MVC – MVC implementation

Spring DAO – JDBC abstraction

Spring ORM – integration with ORM frameworks

Spring AOP – aspect‑oriented programming

3. Common Spring annotations

Web layer annotations:

@Controller, @RestController

@RequestMapping (and shortcut @GetMapping, @PostMapping, @PutMapping, @DeleteMapping)

@ResponseBody, @RequestBody, @PathVariable

Container annotations:

@Component, @Service, @Repository

@Autowired, @Qualifier

@Configuration, @Bean, @Scope

@Value

AOP annotations:

@Aspect, @Pointcut, @Before, @After, @AfterReturning, @AfterThrowing, @Around

4. Design patterns used in Spring

Factory pattern – BeanFactory & ApplicationContext

Proxy pattern – AOP implementation

Singleton – default bean scope

Template method – JdbcTemplate, RestTemplate

Observer – Application events

Adapter – AOP advice adapters

Strategy – Resource loading strategies

5. IoC and DI explained

IoC (Inversion of Control) means the container creates and manages object lifecycles. DI (Dependency Injection) is the concrete way the container injects required collaborators into a bean, either via constructors or setter methods.

6. BeanFactory vs ApplicationContext

BeanFactory is the basic container that creates beans. ApplicationContext extends BeanFactory with additional features such as internationalization, event propagation, and automatic bean post‑processing.

7. Bean lifecycle

The lifecycle consists of four main phases: Instantiation, Property population, Initialization, and Destruction. Spring invokes custom init‑method, @PostConstruct, BeanPostProcessor methods, and finally destroy‑method or @PreDestroy.

8. Bean definition methods

Direct Java code (programmatic registration)

XML configuration files

Annotation‑based configuration

9. Dependency injection methods

Constructor injection

Setter (property) injection

Factory‑method injection (static and instance factories)

10. Bean scopes

singleton – one instance per container (default)

prototype – a new instance each request

request, session, globalSession – web‑specific scopes

11. Singleton bean thread safety

Singleton beans are not thread‑safe by default; they must be stateless or use ThreadLocal/other synchronization mechanisms to avoid concurrency issues.

12. Circular dependencies and three‑level cache

Spring resolves setter‑based circular dependencies using a three‑level cache: singletonObjects (fully initialized beans), earlySingletonObjects (partially initialized beans), and singletonFactories (ObjectFactory for early exposure). Constructor‑based cycles are not supported.

13. @Autowired implementation

The core processor is AutowiredAnnotationBeanPostProcessor. During populateBean, it calls postProcessProperties, which finds injection points and performs the actual injection.

14. AOP fundamentals

Aspect – modularization of cross‑cutting concerns

Joinpoint – a point during program execution (method execution in Spring)

Pointcut – expression that selects joinpoints

Advice – code to execute at a selected joinpoint (Before, After, AfterReturning, AfterThrowing, Around)

Target – the proxied object

Weaving – linking advice to target (runtime in Spring)

Example: logging request and response

@Aspect
@Component
public class WebLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    @Pointcut("@annotation(com.example.WebLog)")
    public void webLog() {}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // log request details
    }

    @After("webLog()")
    public void doAfter() {
        // log end marker
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        logger.info("Response: {}", new ObjectMapper().writeValueAsString(result));
        logger.info("Time‑Consuming: {} ms", System.currentTimeMillis() - start);
        return result;
    }
}

15. JDK dynamic proxy vs CGLIB

JDK proxy works only for interfaces; uses java.lang.reflect.Proxy and InvocationHandler.

CGLIB creates a subclass of the target class (via ASM) and overrides methods; works for concrete classes but cannot proxy final methods.

16. Transaction management

Spring supports programmatic (TransactionTemplate) and declarative (@Transactional) transaction management. Declarative transactions are implemented with AOP proxies that wrap the target method.

Isolation levels

DEFAULT, READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE

Propagation behaviors

REQUIRED (default), SUPPORTS, MANDATORY, REQUIRES_NEW, NOT_SUPPORTED, NEVER, NESTED

Common pitfalls

@Transactional on non‑public methods is ignored.

Self‑invocation within the same class bypasses the proxy, so transactions do not apply.

Incorrect rollbackFor settings may prevent rollback on checked exceptions.

Using @Transactional with propagation settings that suspend or ignore existing transactions.

17. Spring MVC core components

DispatcherServlet – front controller

HandlerMapping – maps requests to handlers

HandlerAdapter – invokes handler methods

HandlerInterceptor – pre‑ and post‑processing

ModelAndView – model data + view name

ViewResolver – resolves logical view names to actual views

MVC request flow

Client sends request to DispatcherServlet.

DispatcherServlet uses HandlerMapping to locate a handler.

HandlerAdapter invokes the handler (controller).

Handler returns ModelAndView.

ViewResolver resolves the view and renders the response.

RESTful flow

When a controller method is annotated with @ResponseBody (or @RestController), the return value is written directly to the HTTP response by a HttpMessageConverter (typically Jackson) without involving a View.

18. Spring Boot overview

Spring Boot provides opinionated defaults, embedded servlet containers, and auto‑configuration to simplify Spring application development.

Auto‑configuration mechanism

The @EnableAutoConfiguration (included in @SpringBootApplication) imports configuration classes listed in META-INF/spring.factories via AutoConfigurationImportSelector. It filters candidates, applies exclusions, and registers the selected @Configuration classes.

Creating a custom starter

@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
    private String name;
    // getters and setters
}

@Configuration
@EnableConfigurationProperties(HelloProperties.class)
public class HelloAutoConfiguration {}

Register the auto‑configuration class in src/main/resources/META-INF/spring.factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.example.HelloAutoConfiguration

19. Spring Cloud basics

Spring Cloud builds on Spring Boot to provide distributed system patterns such as service discovery, load balancing, circuit breaking, and configuration management. Core components include Eureka/Consul for registration, Ribbon for client‑side load balancing, Feign for declarative REST clients, Hystrix for fault tolerance, and Config Server for externalized configuration.

Spring Cloud solves the typical challenges of micro‑service architectures: routing, inter‑service communication, service registration & discovery, and resilience.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

transactionaopMVCIoCspringSpring Bootdependency-injectionSpring Cloud
Sanyou's Java Diary
Written by

Sanyou's Java Diary

Passionate about technology, though not great at solving problems; eager to share, never tire of learning!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.