BeanFactory 是 Spring 最底层的容器接口,只管创建和获取 Bean,而且是懒加载的。ApplicationContext 继承了它,多了事件发布、国际化、资源加载这些能力,会自动处理注解,并且启动时就把所有单例创建好,这样配置有问题启动就会失败。我们平时用的都是 ApplicationContext。
English PitchEnglish · ~50s
Inversion of Control shifts object creation and wiring from your business classes to the Spring container, and Dependency Injection is how Spring delivers those collaborators—ideally via constructor injection. That keeps classes decoupled from concrete implementations, making unit testing straightforward because you can pass mocks directly without booting the container. Under the hood, BeanFactory is the minimal container interface that lazily instantiates beans on demand. ApplicationContext builds on it with event publishing, resource loading, annotation processing, and eager singleton creation at startup—so misconfigurations fail fast rather than in production, which is why we always use ApplicationContext.
Key terms:Inversion of Control, Dependency Injection, BeanFactory, ApplicationContext
Likely follow-up: "Why do you prefer constructor injection over field injection, and how does it behave with circular dependencies?"
我默认用构造器注入。好处有几个:字段可以是 final,对象一创建出来依赖就是齐的,不会出现用到一半发现是 null;依赖都写在构造器参数里,一眼能看出这个类依赖什么,参数太多也提醒我这个类该拆了;单元测试直接 new 一个传 mock 进去就行,不用启动 Spring;循环依赖也会在启动时直接报错。可选的依赖可以用 setter 注入。字段注入虽然写起来短,但依赖是隐藏的,离开容器只能靠反射赋值、没法直接 new 出来传依赖,所以不推荐。
如果一个接口有多个实现,@Autowired 按类型会找到多个,就会报错。解决办法有两个:在其中一个实现上加 @Primary,表示默认用它;或者在注入的地方加 @Qualifier 写明要哪个名字的 Bean。还可以直接注入一个 List 或者 Map,把所有实现都拿到,做策略模式很方便。
English PitchEnglish · ~50s
I default to constructor injection for required dependencies: fields can be final, objects are fully initialized on creation, unit tests can pass mocks via new without booting Spring, and circular dependencies fail fast at startup. Setter injection fits optional dependencies, while field injection hides dependencies and forces reflection in tests, so I avoid it in production code. When multiple beans share a type, @Autowired throws NoUniqueBeanDefinitionException unless disambiguated—you can select a specific bean with @Qualifier at the injection point, mark a default with @Primary, or inject a List or Map to wire every implementation for a strategy pattern.
Spring beans default to singleton—one shared instance per container—alongside prototype, which creates a fresh instance on every lookup, and web scopes like request and session. Crucially, Spring gives zero thread-safety guarantees for singletons; safety depends entirely on keeping them stateless. Services and controllers are safe when they only hold injected collaborators and immutable config, whereas storing per-request data in a mutable field causes race conditions and cross-user data leaks. In production, I keep singletons stateless, pass request data through method parameters, use concurrent collections or locks only when shared mutable state is unavoidable, and confine per-thread context to ThreadLocal (with proper cleanup in thread pools).
过程(A、B 互相字段注入):创建 A → 实例化 A,把 A 的工厂放进三级缓存 → 注入 B,触发创建 B → 实例化 B,注入 A 时从三级缓存拿到 A 的早期引用(放入二级缓存)→ B 初始化完成,放入一级缓存 → 回到 A,注入 B,A 初始化完成。
为什么需要第三级:如果 A 需要被 AOP 代理,B 拿到的必须是代理而不是原始对象。三级缓存里的工厂可以在被循环引用时才提前创建代理;没有循环依赖时,代理仍然在初始化之后创建。
不能解决的情况:
情况
原因
构造器注入
实例化需要对方,对方又需要自己,没有可暴露的早期引用
prototype
不缓存,无法提前暴露
@Async 等在后置处理中换掉了对象
早期引用和最终对象不是同一个
Boot 2.6+ 的默认行为:spring.main.allow-circular-references=false,启动报 The dependencies of some of the beans in the application context form a cycle。可以改配置放开,但更应该消除循环。
循环依赖就是 A 依赖 B,B 又依赖 A。现在 Spring Boot 从 2.6 开始默认是禁止循环依赖的,启动的时候就会报错,告诉你哪几个 Bean 形成了环。官方的态度是循环依赖说明设计有问题,应该去改设计,比如把两边都要用的逻辑抽到第三个类里,或者用事件来解耦。
Spring 框架本身是能处理一部分循环依赖的,条件是单例,并且通过字段或者 setter 注入。原理是三级缓存:A 实例化出来以后,在注入依赖之前,先把自己的早期引用通过一个工厂暴露出去;接着去创建 B,B 需要 A 的时候就能拿到这个早期引用,B 创建完了再回来把 A 装配完。第三级缓存放的是工厂,是为了在有 AOP 的情况下,能提前把代理对象创建出来给 B。
构造器注入的循环依赖解决不了,因为创建 A 就需要 B,创建 B 又需要 A,谁都没法先实例化出来。
正因为是代理,就有一个限制:只有从外面通过代理调进来的才会被拦截。同一个类里一个方法调另一个方法,走的是 this,不经过代理,切面就不生效;private 和 final 方法也拦截不到。这就是事务、异步、缓存注解失效最常见的原因。
English PitchEnglish · ~50s
Spring AOP extracts cross-cutting concerns—like transactions, logging, metrics, and security—out of core business logic so they stay clean and reusable. At runtime, Spring wraps matching beans in a proxy during post-initialization, using JDK dynamic proxies for interfaces or CGLIB subclasses, with Spring Boot defaulting to CGLIB. Every external call hits the proxy first, runs the configured advice, and then delegates to the target method. The biggest production catch is that proxy interception only works on external calls: self-invocation via this, as well as private or final methods, completely bypasses the proxy and silently skips the aspect.
线上最常见的失效有五种:同类内部自调用绕过了代理;方法是 private 或 final 拦截不到;异常被内部 catch 吞掉了;对象是自己 new 出来的;或者开了新线程脱离了当前 ThreadLocal。另外内层事务抛异常、外层 catch 住时,提交会报 UnexpectedRollbackException,因为共用同一个事务已被标记为只能回滚。
最后生产上绝不把外部 HTTP 或 RPC 调用放进事务里,防止下游变慢长时间占着行锁和连接池。
English PitchEnglish · ~65s
@Transactional is powered by an AOP proxy: before entering the method, TransactionInterceptor acquires a database connection via the transaction manager, disables auto-commit, and binds it to the current thread's ThreadLocal. All repository calls on that thread share the connection, committing on normal return or rolling back on unhandled RuntimeException and Error—checked exceptions commit by default unless you specify rollbackFor. In practice, it silently breaks on self-invocation, private or final methods, swallowed exceptions, or work spawned onto another thread, and catching an exception thrown by an inner @Transactional method joining the same transaction still fails on commit with UnexpectedRollbackException because the shared transaction is already marked rollback-only. I also keep external HTTP calls out of transactions so slow downstream dependencies don't hold locks and exhaust the connection pool.
隔离级别 Spring 默认是 DEFAULT,就是用数据库自己的默认值,MySQL 是可重复读,PostgreSQL 是读已提交。
English PitchEnglish · ~55s
Spring defines seven propagation behaviors—REQUIRED, REQUIRES_NEW, NESTED, plus SUPPORTS, NOT_SUPPORTED, MANDATORY, and NEVER—governing how nested transactional calls interact. REQUIRED, the default, joins an existing transaction or starts a new one so inner and outer commit or roll back together. REQUIRES_NEW suspends the outer transaction and starts an independent one on a second connection—ideal for audit logs that must persist even if the outer call fails, though calling it in loops risks exhausting the connection pool. NESTED uses a database savepoint within the same transaction, allowing local rollback without aborting the outer transaction, while still rolling back if the outer one fails.
Likely follow-up: "If an inner REQUIRES_NEW method throws an exception, does the outer transaction automatically roll back, and why does self-invocation break REQUIRES_NEW?"
An incoming HTTP request first passes through the Servlet Filter chain—where CORS and Spring Security run—before hitting DispatcherServlet, Spring MVC's front controller. DispatcherServlet consults HandlerMapping to locate the matching controller method and its HandlerInterceptor chain, then delegates invocation to HandlerAdapter. Before executing your method, argument resolvers bind path variables, query params, and deserialize JSON bodies via HttpMessageConverter while running @Valid validation, then serialize the return value back to JSON. Any exception raised inside MVC flows to @ControllerAdvice, though exceptions thrown in upstream Servlet filters won't reach it.
有两个原则。一是不要把异常的 message 或者堆栈直接返回给客户端,可能泄露内部信息,客户端只拿到错误码和说明,细节记日志。二是校验要分层,格式校验在入口做,业务规则在 Service 做,唯一性这种最终要靠数据库约束。
English PitchEnglish · ~55s
For request validation, I use Bean Validation annotations like @NotBlank and @Min on DTO fields with @Valid on controller parameters—and on nested objects—so invalid input fails fast with MethodArgumentNotValidException before business logic runs, while keeping business rules in services and uniqueness enforced by database constraints. For global error handling, I centralize mappings in @RestControllerAdvice with @ExceptionHandler, translating validation errors to 400 with field details, missing resources to 404, and unexpected failures to 500 using Spring 6's RFC 9457 ProblemDetail. Crucially, I never expose stack traces or raw internal messages to clients—only safe error codes and descriptions, logging full details server-side.
Likely follow-up: "What is the difference between @NotNull, @NotEmpty, and @NotBlank, and why won't @ControllerAdvice catch exceptions thrown inside a Servlet Filter?"
Spring Security operates as a Servlet filter chain running ahead of DispatcherServlet, cleanly separating authentication from authorization. During authentication, a filter extracts credentials—like a password or Bearer JWT—and delegates to AuthenticationManager and its AuthenticationProvider, verifying password hashes via PasswordEncoder or validating the JWT signature and expiry, then storing the authenticated principal in the ThreadLocal-backed SecurityContext. Authorization happens downstream in AuthorizationFilter against URL rules, plus method-level @PreAuthorize checks via AOP proxies—returning 401 when unauthenticated and 403 when forbidden. For stateless APIs, we disable sessions and use short-lived JWTs paired with revocable refresh tokens, keeping sensitive data out of unencrypted JWT payloads.
@SpringBootApplication combines three annotations: @SpringBootConfiguration, @ComponentScan for the current package subtree, and @EnableAutoConfiguration. At startup, Spring Boot discovers candidate auto-configuration classes from every JAR's AutoConfiguration.imports file on the classpath and evaluates their conditional annotations. Conditions like @ConditionalOnClass activate defaults when a starter brings in a library, while @ConditionalOnMissingBean steps aside automatically the moment you define your own bean. That convention-over-configuration design lets you get production-ready defaults quickly without losing full override control, and when something behaves unexpectedly, running with --debug prints the exact condition evaluation report.
Spring Boot layers externalized configuration in strict precedence order—command-line arguments and JVM system properties override environment variables, which override external and packaged application.yml files, with profile-specific files taking priority over defaults. That lets you promote one immutable artifact across environments and inject secrets via environment variables or a secret manager rather than committing them to Git. For binding, @Value is fine for a quick single property, but in production I default to @ConfigurationProperties with @Validated. It groups related settings into a type-safe, relaxed-bound object and fails fast at startup if required config is missing or invalid.
For observability, I pair Spring Boot Actuator with Micrometer to export RED metrics plus JVM, thread-pool, and HikariCP stats to Prometheus, alongside structured JSON logs carrying trace IDs from OpenTelemetry. Sensitive endpoints like /actuator/env and /actuator/heapdump stay locked down on an internal management port. In Kubernetes, I strictly separate liveness and readiness probes: liveness only checks whether the JVM itself is stuck, while readiness checks critical dependencies—putting a database check in liveness causes cascading restarts during transient DB blips. For zero-downtime deploys, I combine a short Kubernetes preStop delay—giving load balancers time to stop routing new traffic before SIGTERM hits—with graceful shutdown so in-flight requests finish cleanly before connections close.
Key terms:Actuator, Micrometer, liveness vs readiness, graceful shutdown
Likely follow-up: "Why do rolling deployments still see brief 502 errors even when graceful shutdown is enabled?"