You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Singleton作用域与Application作用域的区别及示例说明

Spring Singleton vs Application Scope: Core Differences & Examples

Great question! I see this confusion all the time—singleton and application scope do sound identical at first glance, but they operate at totally different levels. Let’s break down the key differences and show you concrete examples to make it click.

Core Differences

Let’s start with the most critical distinctions:

  • Scope Boundary
    • Singleton: Tied to a single Spring ApplicationContext. If your app uses multiple Spring containers (like a parent root context and child DispatcherServlet context in Spring MVC), each container will create its own separate instance of a singleton bean.
    • Application: Tied to your web app’s ServletContext. There’s only one ServletContext per web application, so an application-scoped bean is a single instance shared across all Spring containers in that web app.
  • Environment Support
    • Singleton: Works in both web and non-web Spring apps (like standalone console apps or Spring Boot desktop tools).
    • Application: Only works in web applications—it depends on the ServletContext, which is part of the Java Servlet spec and doesn’t exist in non-web environments.
  • Lifecycle Alignment
    • Singleton: Created when its parent Spring container starts, destroyed when that container shuts down.
    • Application: Created when the ServletContext initializes (when the web app starts), destroyed when the ServletContext is destroyed (when the entire web app stops, not just a single Spring container).

Example 1: Singleton Scope in Multiple Spring Containers

Let’s use a common Spring MVC scenario where we have two nested Spring containers:

  1. A root ApplicationContext (loaded via ContextLoaderListener, holds services/repositories)
  2. A child DispatcherServlet ApplicationContext (holds controllers and web-specific beans)

First, define a singleton bean:

@Component
@Scope("singleton")
public class AppCounter {
    private int count = 0;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

Inject this bean into a service in the root context:

@Service
public class RootService {
    @Autowired
    private AppCounter rootCounter;

    public void trackActivity() {
        rootCounter.increment();
        System.out.println("Root Context Counter: " + rootCounter.getCount());
    }
}

Then inject the same bean into a controller in the child context:

@Controller
public class WebController {
    @Autowired
    private AppCounter webCounter;

    @GetMapping("/track")
    public String track(Model model) {
        webCounter.increment();
        model.addAttribute("webCount", webCounter.getCount());
        return "track-page";
    }
}

What Happens When You Run This?

  • Call rootService.trackActivity() once: the root counter becomes 1.
  • Hit the /track endpoint once: the web counter becomes 1.

These are two separate instances—each Spring container creates its own singleton.

Example 2: Application Scope Across Containers

Now update the bean’s scope to application:

@Component
@Scope("application")
// Optional: For web apps, you can use @ApplicationScope as a shortcut
public class AppCounter {
    private int count = 0;

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

Run the same scenario again:

  • Call rootService.trackActivity() once: counter becomes 1.
  • Hit the /track endpoint once: counter becomes 2.

Both the root service and web controller are using the same single instance stored in the ServletContext—shared across all Spring containers in the web app.

One More Gotcha

Try using @Scope("application") in a non-web Spring app (like a standalone Spring Boot console app). You’ll get an error immediately, because there’s no ServletContext to bind the bean to. Singleton scope works perfectly here, though.

Final Takeaway

  • Use Singleton when you want one instance per Spring container (works everywhere).
  • Use Application when you need one instance across your entire web application (even across multiple Spring containers).

内容的提问来源于stack exchange,提问作者S. Najim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:37:15