As Java supports multithreading, most of the services written in Java deals with processing multiple requests at the same time. To get more details about current request processing, context is used.
If you want to create an object in one class which is used in multiple subsequent classes, one way to do it is to pass the object as parameter to the methods in the chain till it reaches the class where it is used. As this is not convenient approach if multiple objects should be shared/if the object passed to the method is not used (will be passed to another method in the chain), Java provides you to define a context. With context, you can create an object at one stage and add it to the context which can be retrieved at later stages.
Some examples of creating context are:
ThreadLocal: this is used to create context per thread, used to store and retrieve objects within the thread.
ServletContext: this is another common use of context in Java. Also, each HttpServletRequest object can be used to get session under which the request is getting processed, this is based on the same concept.
Spring applicationContext: this is used to get beans configured used Spring.
If you are creating custom context, you need to manage its life cycle.
Hope this answers your question. Let me know if I missed including any important information.
由于 Java 支持多线程,大多数用 Java 编写的服务都要同时处理多个请求。要获取有关当前请求处理的更多详细信息,需要使用上下文。
如果要在一个类中创建一个对象,并在多个后续类中使用该对象,一种方法是将该对象作为参数传递给链中的方法,直到该对象到达使用它的类为止。如果需要共享多个对象,或者如果传递给方法的对象没有被使用(将被传递给链中的另一个方法),这种方法并不方便,因此 Java 提供了定义上下文的功能。通过上下文,您可以在一个阶段创建一个对象,并将其添加到上下文中,以便在以后的阶段检索。
创建上下文的一些示例如下
ThreadLocal:用于为每个线程创建上下文,用于在线程内存储和检索对象。
ServletContext:这是 Java 中上下文的另一种常见用法。此外,每个 HttpServletRequest 对象都可用于获取处理请求的会话,这是基于相同的概念。
Spring applicationContext:用于获取使用 Spring 配置的 Bean。
如果要创建自定义上下文,则需要管理其生命周期。