Annotation Interface Rest
Usually used on a subclass of RestServlet, but can be used to annotate any class that you want to expose as
a REST resource.
Default response format (content negotiation):
The response format is not hardwired to JSON. The serializer used to render a response body is chosen by
ordinary HTTP content negotiation — the request's serializers (see Serializer.getMediaTypeRanges()). A request that
sends no
In the default configuration (BasicRestServlet / BasicRestResource, via
BasicUniversalConfig) the serializer set lists HTML first, so a browser
— or any client that omits serializers() for how serializer ordering determines
this default.
See Also:
-
Optional Element Summary
Optional ElementsModifier and TypeOptional ElementDescriptionAllowed header URL parameters.Allowed method headers.Allowed method parameters.String[]Allowed parser session option keys for this resource (ordered merge, prefix-keyremoves a key).String[]Allowed serializer session option keys for this resource (ordered merge, prefix-keyremoves a key).Names theExecutorbean used to routeCompletableFuturecompletion callbacks through a dedicated thread pool.Configurable timeout (milliseconds) applied toCompletableFuture-returning handlers byAsyncResponseProcessor.Class<? extends RestAuthenticator>Resource-level authenticator.Class<?>[]REST children.Child[]Rich child definitions — the host-side seed form ofchildren().Client version header.Optional location of configuration file for this servlet.String[]Supported content media types.Class<? extends RestConverter>[]Class-level response converters.Opt the resource into REST-driven serializer/parser debug behavior.DefaultAccept header.Default character encoding.DefaultContent-Type header.String[]Default request attributes.String[]Default request headers.String[]Default response headers.String[]Optional servlet description.Disable content URL parameter.Eagerly initializes framework-managed memoizers duringRestContextconstruction.Specifies the compression encoders for this resource.FormData[]Default form data parameter definitions.Class-level guards.Header[]Default header parameter definitions.Opt this parent resource into deferred (first-invocation) construction of itschildren()sub-resources.The maximum allowed input size (in bytes) on HTTP requests.booleanMixin-declared opt-in: fold this class's ownresponseProcessorsinto the host resource's chain whenever this class is composed as a mixin via a plain@Rest(mixins=...)reference.Messages.Mixin[]Rich mixin definitions — the host-side override form ofmixins().Class<?>[]REST mixins.String[]Property names for which less-derived contributions are NOT inherited.Per-resource observability opt-in / opt-out control.Class<? extends OpenApiProvider>OpenAPI 3.1 provider.Class<?>[]Specifies the parsers for converting HTTP request bodies into POJOs.Class<? extends HttpPartParser>HTTP part parser.Class<? extends HttpPartSerializer>HTTP part serializer.Resource path.Path[]Default path parameter definitions.String[]Additional servlet mount paths.String[]Supported accept media types.Query[]Default query parameter definitions.Render response stack traces in responses.Class<? extends ResponseProcessor>[]Response processors.Java REST operation method parameter resolvers.Role guard.Declared roles.Class<? extends Serializer>[]Specifies the serializers for POJOs into HTTP response bodies.Optional site name.Class<? extends StaticFiles>Static files.Provides swagger-specific metadata on this resource.Class<? extends SwaggerProvider>Swagger provider.String[]Optional servlet title.Resource authority path.Resource context path.URI-resolution relativity.URI-resolution.Opt this resource into per-request virtual-thread dispatch (Java 21+).
-
Element Details
-
allowedHeaderParams
Allowed header URL parameters.When specified, allows headers such as
"Accept" and"Content-Type" to be passed in as URL query parameters.
For example:?Accept=text/json&Content-Type=text/json
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ). -
Use
"*" to represent all methods. -
Use
"NONE" (case insensitive) to suppress inheriting a value from a parent class.
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
allowedMethodHeaders
Allowed method headers.A comma-delimited list of HTTP method names that are allowed to be passed as values in an
X-Method ,X-HTTP-Method-Override ,X-HTTP-Method orX-Method-Override HTTP header to override the real HTTP method name. All four headers share this list; when more than one is sent they are tried in that order.Allows you to override the actual HTTP method with a simulated method.
For example, if an HTTP Client API doesn't supportPATCH but does supportPOST (becausePATCH is not part of the original HTTP spec), you can add aX-Method: PATCH header on a normalHTTP POST /foo request call which will make the HTTP call look like aPATCH request in any of the REST APIs.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ). - Method names are case-insensitive.
-
Use
"*" to represent all methods. -
Use
"NONE" (case insensitive) to suppress inheriting a value from a parent class. -
Once the list admits at least one method, override claims must agree: a request whose override headers (or
method query parameter) name more than one distinct method is refused with400 , whether or not the list admits them. -
On a safe request (
GET ,HEAD ,OPTIONS ,TRACE ), an override is honored only when it names another safe method or an operation declaredread=true; anything else is refused with405 . Overrides on aPOST are unaffected.
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
allowedMethodParams
Allowed method parameters.When specified, the HTTP method can be overridden by passing in a
"method" URL parameter.
For example:?method=OPTIONS
On a safe request (
GET ,HEAD ,OPTIONS ,TRACE ), which is what a link or a typed URL sends, the parameter may only name another safe method or a custom method whose operation is declaredread=true. Anything else, for exampleGET /foo?method=DELETE , is refused with405 Method Not Allowed , so a link can never trigger a write. On aPOST , the parameter may name any method in this list.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ). -
Use
"*" to represent all methods. -
Use
"NONE" (case insensitive) to suppress inheriting a value from a parent class.
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
authenticator
Class<? extends RestAuthenticator> authenticatorResource-level authenticator.Resolves the
Principaland roles for requests to this resource and its descendant child resources (inherited unless cut off vianoInherit={"authenticator"}), so thatroleGuard/RoleBasedRestGuard/@Auth/isUserInRoleresolve against the computed identity.Notes:
- The implementation is instantiated through the resource's bean store (constructor injection).
-
The default
RestAuthenticator.Nullsentinel means "not specified."
See Also:
- Returns:
- The annotation value.
- Since:
- 10.0.0
- Default:
- org.apache.juneau.rest.server.auth.RestAuthenticator.Null.class
-
children
REST children.Defines children of this resource. Each child resource is mounted under its own URL subtree (per the child's own
@Rest(path=...)/@Rest(paths=...)) and constructs its ownRestContext.Children vs. mixins (resolution semantics)
Children are isolated from the parent's resolution chain by design — a child's serializers, parsers, guards, hooks, etc. are all resolved against the child's own
RestContextonly, NOT walked through the parent. This is the opposite of howmixinsresolve. See the Mixin-vs-child divergence topic for the rationale (children own their lifecycle and are externally mounted; mixins are inline composers sharing the host's URL namespace and resolution chain).Inheritance Rules
- Children on child are combined with those on parent class.
- Children are list parent-to-child in the order they appear in the annotation.
See Also:
- Child Resources
- REST Server — Mixin Sub-Contexts (for the mixin-vs-child divergence)
- Returns:
- The annotation value.
- Default:
- {}
-
childrenDefs
Rich child definitions — the host-side seed form ofchildren().Each
@Childentry names a child class (viaChild.type()) and lets the host seed a curated set of@Rest-level settings onto that child's otherwise-isolatedRestContext— guards, role guards, part serializer/parser, and a handful of default-scalar settings — without editing the child class.Unlike
mixinDefs, this does not override an inherited chain (children never inherit from the host); it seeds settings onto an isolated context. Additive-security seed members (guards,converters,roleGuard,rolesDeclared) can't be removed or weakened by the child; the remaining scalar seed members are a fallback the child's own explicit@Restdeclaration wins over. SeeChildfor the full semantics.Example:
@Rest ( childrenDefs=@Child (type=FooChild.class , maxInput="10M" ) )public class MyResource { ... }This attribute is additive to
children(): bare-class entries inchildren()and rich entries here are discovered together (bare classes first, thenchildrenDefs). A@Child(type=X.class)with no seed members is the exact equivalent of a barechildren=X.classentry.See Also:
- Returns:
- The annotation value.
- Since:
- 10.0.0
- Default:
- {}
-
mixins
REST mixins.Defines operation-provider classes whose
@RestOp-group methods should be composed into this resource.Mixin methods are discovered the same way as local operation methods and surface under this resource's URL namespace. On path/method collisions, local methods on this resource win over mixin methods.
Per-mixin RestContext + host-to-mixin inheritance (since 10.0.0)
Each mixin class is elevated to its own
RestContextparent-linked to this host'sRestContext. The mixin's class-level@Rest(...)configuration applies to its own endpoints, with inheritance from the host:- List-shaped properties (
serializers,parsers,encoders,converters,responseProcessors,restOpArgs,guards) — host's chain runs first, then the mixin's appended. Host endpoints see only the host's chain. - Replace-shaped properties (
partSerializer,partParser) — the mixin's value wins over the host's for mixin endpoints when declared; otherwise the host's value is inherited. messages— the mixin's bundle is chained as a child of the host's viaMessages.chain(child, parent)so mixin keys win and missing keys fall through to the host.- Lifecycle hooks (
@RestStartCall,@RestEndCall,@RestPreCall,@RestPostCall,@RestDestroy) — dual-fire host-then-mixin for mixin-endpoint requests; host-only for host-endpoint requests.
Use
@Rest(noInherit={...})on a mixin class to cut off inheritance for a specific property — same token set as the host'snoInheritmachinery (e.g."serializers","guards","messages").Mixins vs. children
Mixins are inline composers that share the host's URL namespace and inherit from the host's resolution chain.
Childrenare independently-mounted resources isolated from the host's resolution chain. See the Mixin-vs-child divergence topic for the rationale.Inheritance Rules
- Mixins on child are combined with those on parent class.
- Mixins are listed parent-to-child in the order they appear in the annotation.
- Transitive mixins (
Amixes inB) parent-link flat to the host — bothAandBgetparentContext = host, never anA → Bchain.
For host-side per-mixin setting overrides (applying guards / serializers / a mount path / etc. to a specific mixin's endpoints without editing the mixin class), see the rich
mixinDefscompanion attribute.See Also:
- Returns:
- The annotation value.
- Default:
- {}
- List-shaped properties (
-
mixinDefs
Rich mixin definitions — the host-side override form ofmixins().Each
@Mixinentry names a mixin class (viaMixin.type()) and lets the host override selected@Rest-level settings for that mixin's mixed-in endpoints — guards, role guards, serializers, default headers, mount path, etc. — without subclassing or editing the mixin class.Example:
@Rest ( mixinDefs=@Mixin (type=FooMixin.class , guards=AdminGuard.class ) )public class MyResource { ... }This attribute is additive to
mixins(): bare-class entries inmixins()and rich entries here are discovered together (bare classes first, thenmixinDefs). A@Mixin(type=X.class)with no overrides is the exact equivalent of a baremixins=X.classentry.See Also:
- Returns:
- The annotation value.
- Since:
- 10.0.0
- Default:
- {}
-
mergeResponseProcessorsIntoHost
boolean mergeResponseProcessorsIntoHostMixin-declared opt-in: fold this class's ownresponseProcessorsinto the host resource's chain whenever this class is composed as a mixin via a plain@Rest(mixins=...)reference.By default (
false) a mixin'sresponseProcessorsapply only to the mixin's own endpoints — a host's own@RestOpmethods see only the host's chain (the standardmixininheritance rule "host's chain runs first, then the mixin's appended; host endpoints see only the host's chain"). Setting this totrueon the mixin class itself makes a plain@Rest(mixins=ThisClass.class)reference additionally append this class's ownresponseProcessorsto the end of the host's own chain, so the host's own endpoints pick them up too.This is the mixin-declared, response-processor-scoped counterpart to
@Mixin(mergeIntoHost=true)(which is host-declared and folds all list-shaped attributes). UnlikemergeIntoHost, this directive lives with the mixin and folds onlyresponseProcessors— neverguards,serializers, or any other list-shaped attribute. It is intended for view-renderer mixins (e.g.FreemarkerMixin) so that declaring the mixin is enough to route the host's ownViewreturns through the renderer.Strictly opt-in and non-silent: it has no effect for a mixin that leaves it
false, so existing mixins keep today's scoping exactly. Same-class de-duplication applies, so a response processor the host already declares is not added twice.- Returns:
- The annotation value.
- Since:
- 10.0.0
- Default:
- false
-
clientVersionHeader
Client version header.Specifies the name of the header used to denote the client version on HTTP requests.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
config
Optional location of configuration file for this servlet.The configuration file .
Inheritance Rules
- Config file is searched for in child-to-parent order.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ). -
Use the keyword
SYSTEM_DEFAULT to refer to the system default configuration returned by theConfig.getSystemDefault().
- Returns:
- The annotation value.
- Default:
- ""
-
eagerInit
Eagerly initializes framework-managed memoizers duringRestContextconstruction.When enabled, framework bean memoizers and operation/child-context memoizers are force-fired inside the constructor try/catch so startup-time configuration errors fail fast.
This setting is disabled by default.
"true" - Force eager initialization during context construction."false" - Keep initialization lazy until first use (default).
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
lazyChildren
Opt this parent resource into deferred (first-invocation) construction of itschildren()sub-resources.When
"true", theRestContextinstances for all@Rest(children=...)entries are not built at parent startup. Instead, each child's routing entry is registered immediately (so URL matching is fully operational from the first request), but the fullRestContext— including all of its bean-store setup, memoizers, and lifecycle hooks — is constructed on the first inbound request to that child's URL prefix. Subsequent requests reuse the already-built context.This is particularly useful when a parent resource exposes heavyweight admin or diagnostic children that are rarely invoked in production. Setting
lazyChildren="true"on the parent lets the parent boot fast; each child pays its construction cost only when (and if) it is first accessed."true" - Children are constructed on first invocation (deferred)."false" (default) - Children are constructed eagerly at parent startup.
Notes:
- The first request to a lazy child pays the full construction cost, which can be significant for heavyweight children. If predictable first-request latency is required, do not opt in.
- Concurrent first-requests to the same lazy child are serialized: only one thread runs the construction; others block until it completes.
-
A lazy child that is never invoked is never constructed. Its lifecycle
@RestDestroy/ shutdown hooks are skipped at parent destruction time. -
The programmatic knob
RestContext.Builder.lazyChildInit(boolean)overrides this annotation. -
Supports REST Server SVL Variables
(e.g.
"$E{LAZY_CHILDREN,false}" ).
See Also:
RestContext.Builder.lazyChildInit(boolean)children()
- Returns:
- The annotation value.
- Default:
- ""
-
consumes
Supported content media types.Overrides the media types inferred from the parsers that identify what media types can be consumed by the resource.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- {}
-
Supports REST Server SVL Variables
(e.g.
-
allowedSerializerOptions
Allowed serializer session option keys for this resource (ordered merge, prefix-keyremoves a key).Comma-delimited list of session property keys (e.g.
"escapeSolidus,maxIndent" ) that clients may send via the"X-Juneau-Serializer-Options" header or"juneauSerializerOptions" query parameter. Keys not in the effective allowlist cause a400 Bad Requestresponse.Entries are merged in application order. A leading hyphen removes a previously added key:
"-escapeSolidus" . Method-levelRestGet.allowedSerializerOptions()values are always merged on top. UsenoInherit()to prevent inheriting less-derived contributions.See Also:
- Returns:
- The annotation value.
- Default:
- {}
-
allowedParserOptions
Allowed parser session option keys for this resource (ordered merge, prefix-keyremoves a key).Comma-delimited list of session property keys that clients may send via the
"X-Juneau-Parser-Options" header or"juneauParserOptions" query parameter. Parser options are ignored for operations without a request-body parser. Keys not in the effective allowlist cause a400 Bad Requestresponse.Use
noInherit()to prevent inheriting less-derived contributions.See Also:
- Returns:
- The annotation value.
- Default:
- {}
-
noInherit
Property names for which less-derived contributions are NOT inherited.Accepted values include
"allowedParserOptions","allowedSerializerOptions","allowedHeaderParams","allowedMethodHeaders","allowedMethodParams","disableContentParam","renderResponseStackTraces","problemDetails","debugMarshalling","eagerInit","lazyChildren","clientVersionHeader","uriAuthority","uriContext","uriRelativity", and"uriResolution". Each entry is SVL-resolved then comma-split. Prevents the named property from inheriting values from parent@Restannotations (router hierarchy). ThenoInheritattribute itself is never inherited.Mixin sub-contexts (since 10.0.0)
On a class declared via
@Rest(mixins=...)on a host,noInheritalso blocks the host-to-mixin inheritance walk for the named property. The token set extends to every contribution list exposed by@Rest:"serializers","parsers","encoders","converters","responseProcessors","restOpArgs","guards","partSerializer","partParser", and"messages". For example,@Rest(noInherit={"guards"})on a mixin removes the host's guard chain from the mixin's endpoints (typical pattern for deliberately-unguarded probes likeHealthMixin).See Also:
- Session Options via HTTP
- REST Server — Mixin Sub-Contexts (for the per-property opt-out semantics)
- Returns:
- The annotation value.
- Default:
- {}
-
converters
Class<? extends RestConverter>[] convertersClass-level response converters.Associates one or more
converterswith a resource class.Inheritance Rules
- Converters on child are combined with those on parent class.
- Converters are executed child-to-parent in the order they appear in the annotation.
- Converters on methods are executed before those on classes.
- Returns:
- The annotation value.
- Default:
- {}
-
defaultAccept
DefaultAccept header.The default value for the
Accept header if not specified on a request.This is a shortcut for using
defaultRequestHeaders()for just this specific header.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
defaultCharset
Default character encoding.The default character encoding for the request and response if not specified on the request.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
See Also:
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
defaultContentType
DefaultContent-Type header.The default value for the
Content-Type header if not specified on a request.This is a shortcut for using
defaultRequestHeaders()for just this specific header.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
defaultRequestAttributes
Default request attributes.Specifies default values for request attributes if they're not already set on the request.
Affects values returned by the following methods:
Example:
// Defined via annotation resolving to a config file setting with default value. @Rest (defaultRequestAttributes={"Foo=bar" ,"Baz: $C{REST/myAttributeValue}" })public class MyResource {// Override at the method level. @RestGet (defaultRequestAttributes={"Foo: bar" })public Object myMethod() {...} }Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
See Also:
- Returns:
- The annotation value.
- Default:
- {}
-
Supports REST Server SVL Variables
(e.g.
-
defaultRequestHeaders
Default request headers.Specifies default values for request headers if they're not passed in through the request.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- {}
-
Supports REST Server SVL Variables
(e.g.
-
defaultResponseHeaders
Default response headers.Specifies default values for response headers if they're not set after the Java REST method is called.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- {}
-
Supports REST Server SVL Variables
(e.g.
-
description
Optional servlet description.It is used to populate the Swagger description field.
Inheritance Rules
- Description is searched for in child-to-parent order.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ). -
The format is plain-text.
Multiple lines are concatenated with newlines.
- Returns:
- The annotation value.
- Default:
- {}
-
disableContentParam
Disable content URL parameter.When enabled (the default — this attribute is
false unless explicitly set), the HTTP request content on PUT and POST requests can be passed in as text using the"content" URL parameter, letting a caller exercise an endpoint's body-consuming logic straight from a URL (handy for a quick manual test or a bookmarked link) without an actual PUT/POST body.
For example:?content=(name='John%20Smith',age=45)
Because the override is on by default, treat it the same way as any other feature that lets untrusted URL content reach parsing/business logic: a link to a PUT/POST endpoint with a crafted
"content" parameter is just as reproducible by a third party (e.g. embedded in a page that an authenticated user happens to load) as the equivalent real request body would be. The override is deliberately restricted toPUT /POST methods so that a simple cross-originGET (the kind a browser issues with no preflight and no caller-controlled header for something as ordinary as an<img src=...>tag) can never trigger it this way, but resources that don't already validate that PUT/POST submissions are same-site in origin (e.g. with a token check, a custom-header check, orSameSite cookies) gain no additional protection here. Set this totrue to disable the override entirely on any resource where it isn't a deliberate feature.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
problemDetails
Opt the resource into RFC 7807 / RFC 9457application/problem+jsonerror responses.When enabled, the resource:
- Emits
application/problem+jsonfor thrownBasicHttpExceptions — regardless of the client'sAcceptheader. The body is a serializedProblempopulated from the exception's status code, reason phrase, and message. - Honors the client's
Acceptheader on the success path. When a@RestOpmethod returns aProblem(or throws aProblemException), theProblemDetailsProcessoronly serializes it asapplication/problem+jsonwhen theAcceptheader matches that media type (or*/*).
"true" — enable problem-details responses for this resource."false" — disable problem-details responses for this resource (overrides an inherited"true"from a parent@Rest)."" (default) — inherit from the next-most-derived@Restin the resource-class hierarchy. Default behavior (no opt-in anywhere in the chain) is unchanged from prior releases.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ). -
Use
noInherit()to prevent inheriting an opt-in from a parent@Rest.
See Also:
- Returns:
- The annotation value.
- Default:
- ""
- Emits
-
debugMarshalling
Opt the resource into REST-driven serializer/parser debug behavior.When enabled, the REST layer forces
Context.debugon the serializer/parser sessions it creates to handle requests for this resource — engaging recursion-detection-that-throws (a genuine cycle throwsMarshallingRecursionExceptioninstead of being size-guard-truncated), parse-input buffering (parse errors can quote the offending input), and stack-trace-prefixed marshalling exceptions.This is a behavior switch, independent of the JUL logger level: raising a logger to
FINE/FINESTchanges logging verbosity only and never changes marshalling behavior. A serializer/parser configured withContext.debugdirectly is unaffected by this setting."true" — enable marshalling debug for this resource."false" — disable marshalling debug for this resource (overrides an inherited"true"from a parent@Rest)."" (default) — inherit from the next-most-derived@Restin the resource-class hierarchy. Default behavior (no opt-in anywhere in the chain) is marshalling debug OFF.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ). -
Use
noInherit()to prevent inheriting an opt-in from a parent@Rest.
- Returns:
- The annotation value.
- Default:
- ""
-
virtualThreads
Opt this resource into per-request virtual-thread dispatch (Java 21+).When enabled, every
@RestOp-annotated handler invocation on this resource is submitted to aExecutors.newVirtualThreadPerTaskExecutor()virtual-thread-per-task executor lazily built by theRestContext. The platform request thread blocks on the virtual thread's completion (so the handler's return value, exceptions, and observability hooks are preserved verbatim), but blocking I/O inside the handler now parks a virtual thread instead of the carrier — i.e. the carrier thread is freed to service other concurrent requests while the handler is parked on socket / file / lock waits. Combined withCompletableFuturereturn types (@RestGet/@RestPostreturningCompletableFuture<T>) this is the high-throughput pattern.Graceful degradation on Java 17/18/19/20: the flag is detected during
RestContextinitialization. If the runtime is older than Java 21, a one-shotWARNINGis logged and the resource falls back to the standard caller-thread dispatch path — no runtime error.Per-
@RestOpoverrides are available viaRestOp.virtualThreads(); the op-level setting takes precedence over the resource-level setting."true" — enable virtual-thread dispatch on Java 21+ (silently disabled on older JVMs)."false" — explicitly disable."" (default) — inherit from the next-most-derived@Restin the resource-class hierarchy.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$E{ENABLE_VIRTUAL_THREADS,false}" ). -
Synchronized blocks and JNI calls in handler code pin a virtual thread to its carrier thread
— prefer
ReentrantLockoversynchronizedin handlers run under this flag.
See Also:
- Returns:
- The annotation value.
- Default:
- ""
-
observability
Per-resource observability opt-in / opt-out control.Controls whether the observability block (
MetricsRecorder/TracerHook) fires for operations on this resource. Per-operation overrides are available viaRestOp.observability()(and the verb annotations)."true" — strict opt-in: the resource requires a wired observability backend. If neither a@Bean MetricsRecordernor a@Bean TracerHookis registered when theRestContextis built, construction fails with a precise error. All operations on this resource have observability enabled."false" — explicit opt-out: the observability block is short-circuited for every operation on this resource, even when a wired backend is present. Also suppressesTraceContextResponseProcessorheader injection for this resource."" (default) — inherits the existing behavior: the observability block runs per-op, but a missing@Beansilently falls back to the NoOp singleton — no startup error.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$E{ENABLE_OBSERVABILITY,false}" ). -
Per-operation overrides via
RestOp.observability()(or verb annotations) take precedence over this resource-level setting.
See Also:
- Returns:
- The annotation value.
- Since:
- 10.0.0
- Default:
- ""
-
asyncTimeoutMillis
Configurable timeout (milliseconds) applied toCompletableFuture-returning handlers byAsyncResponseProcessor. Default is 30,000 ms.On timeout, the future is cancelled with
mayInterruptIfRunning=trueand the response is committed as504 Gateway Timeout. Set to"0"to disable the timeout entirely.Per-
@RestOpoverrides are available viaRestOp.asyncTimeoutMillis(); the op-level setting takes precedence over the resource-level setting.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$E{ASYNC_TIMEOUT_MS,30000}" ).
See Also:
- Returns:
- The annotation value.
- Since:
- 10.0.0
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
asyncCompletionExecutor
Names theExecutorbean used to routeCompletableFuturecompletion callbacks through a dedicated thread pool.When set, the
AsyncResponseProcessorswitches fromfuture.whenComplete(callback)tofuture.whenCompleteAsync(callback, executor), so the response-handler work runs on the named pool instead of the future's natural completion thread (often an I/O-driver or database-callback thread).The value is the
@Bean(name=...)lookup key for anExecutorregistered in the resource's bean store. Empty string (default) means no override — completion callbacks run on the future's natural thread (the existing behavior).Example:
@Rest (path="/api" , asyncCompletionExecutor="myCompletionPool" )public class ApiResourceextends RestServlet {@Bean (name="myCompletionPool" )public Executor completionPool() {return Executors.newFixedThreadPool(8); }@RestGet ("/orders/{id}" )public CompletableFuture<Order> getOrder(@Path String id) {return orderService.fetchAsync(id);// callback runs on myCompletionPool } }Per-operation overrides are available via
RestOp.asyncCompletionExecutor()(and the verb annotations). A reference to a bean name that does not resolve in the bean store causes a startup failure.Notes:
-
MDC propagation still works when this executor is set — the
MdcAsyncListenerwraps the callback before it is routed through the executor, so the MDC snapshot is restored on whichever thread the executor picks.
See Also:
- Returns:
- The annotation value.
- Since:
- 10.0.0
- Default:
- ""
-
MDC propagation still works when this executor is set — the
-
encoders
Specifies the compression encoders for this resource.Encoders are used to enable various kinds of compression (e.g.
"gzip" ) on requests and responses.Encoders are automatically inherited from
encoders()annotations on parent classes with the encoders on child classes prepended to the encoder group. TheEncoderSet.NoInheritclass can be used to prevent inheriting from the parent class.Example:
// Define a REST resource that handles GZIP compression. @Rest ( encoders={ GzipEncoder.class } )public class MyResource { ... }The encoders can also be tailored at the method level using
RestOp.encoders()(and related annotations).For programmatic equivalents, contribute an
EncoderSetbean via@Bean(name="encoders").Inheritance Rules
- Encoders on child are combined with those on parent class.
See Also:
- Returns:
- The annotation value.
- Default:
- {}
-
formDataParams
Default form data parameter definitions.Provides default values for
@FormDataannotations on method parameters across all methods in this class.Example:
@Rest ( formDataParams={@FormData (name="action" , def="submit" ) } )public class MyResource {...}- Returns:
- The annotation value.
- Since:
- 9.2.0
- Default:
- {}
-
guards
Class-level guards.Associates one or more
RestGuardswith all REST methods defined in this class.Inheritance Rules
- Guards on child are combined with those on parent class.
- Guards are executed child-to-parent in the order they appear in the annotation.
- Guards on methods are executed before those on classes.
- Returns:
- The annotation value.
- Default:
- {}
-
headerParams
Default header parameter definitions.Provides default values for
@Headerannotations on method parameters across all methods in this class.Example:
@Rest ( headerParams={@Header (name="Accept-Language" , def="en-US" ),@Header (name="X-API-Version" , def="1.0" ) } )public class MyResource {...}- Returns:
- The annotation value.
- Since:
- 9.2.0
- Default:
- {}
-
maxInput
The maximum allowed input size (in bytes) on HTTP requests.Useful for alleviating DoS attacks by throwing an exception when too much input is received instead of resulting in out-of-memory errors which could affect system stability.
Applies uniformly across body-reading paths, including
multipart/form-datauploads: a request whose declaredContent-Lengthor parsed part sizes exceed this ceiling is rejected with a413response before (or as soon as) the oversized content would otherwise be buffered.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
See Also:
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
messages
Messages. Identifies the location of the resource bundle for this class.There are two possible formats:
- A simple string - Represents the
nameof the resource bundle.
Example:// Bundle name is Messages.properties. @Rest (messages="Messages" ) - Simplified JSON - Represents parameters for the
Messages.Builderclass.
Example:// Bundles can be found in two packages. @Rest (messages="{name:'Messages',baseNames:['{package}.{name}','{package}.i18n.{name}']" )
If the bundle name is not specified, the class name of the resource object is used.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
- A simple string - Represents the
-
parsers
Specifies the parsers for converting HTTP request bodies into POJOs.Parsers are used to convert the content of HTTP requests into POJOs.
Any of the Juneau framework parsers can be used in this setting.
The parser selected is based on the requestContent-Type header matched against the values returned by the following method using a best-match algorithm:Parsers are automatically inherited from
parsers()annotations on parent classes with the parsers on child classes prepended to the parser group. TheParserSet.NoInheritclass can be used to prevent inheriting from the parent class.Example:
// Define a REST resource that can consume JSON and XML. @Rest ( parsers={ JsonParser.class , XmlParser.class } )public class MyResource { ... }The parsers can also be tailored at the method level using
RestOp.parsers()(and related annotations).For programmatic equivalents, contribute a
ParserSetbean via@Bean(name="parsers").Inheritance Rules
- Parsers on child override those on parent class.
ParserSet.Inheritclass can be used to inherit and augment values from parent.ParserSet.NoInheritclass can be used to suppress inheriting from parent.- Parsers on methods take precedence over those on classes.
See Also:
- Returns:
- The annotation value.
- Default:
- {}
-
partParser
Class<? extends HttpPartParser> partParserHTTP part parser.Specifies the
HttpPartParserto use for parsing headers, query/form parameters, and URI parts.- Returns:
- The annotation value.
- Default:
- org.apache.juneau.marshall.httppart.HttpPartParser.Void.class
-
partSerializer
Class<? extends HttpPartSerializer> partSerializerHTTP part serializer.Specifies the
HttpPartSerializerto use for serializing headers, query/form parameters, and URI parts.- Returns:
- The annotation value.
- Default:
- org.apache.juneau.marshall.httppart.HttpPartSerializer.Void.class
-
path
Resource path.Used in the following situations:
-
On child resources (resource classes attached to parents via the
children()annotation) to identify the subpath used to access the child resource relative to the parent. -
On top-level
RestServletclasses deployed as Spring beans whenJuneauRestInitializer is being used.
On child resources
The typical usage is to define a path to a child resource relative to the parent resource.
Example:
@Rest ( children={ChildResource.class } )public class TopLevelResourceextends BasicRestServlet {...}@Rest ( path="/child" , children={GrandchildResource.class } )public class ChildResource {...}@Rest ( path="/grandchild" )public class GrandchildResource {@RestGet ("/" )public String sayHello() {return "Hello!" ; } }In the example above, assuming the
TopLevelResource servlet is deployed to path/myContext/myServlet , then thesayHello method is accessible through the URI/myContext/myServlet/child/grandchild .Note that in this scenario, the
path attribute is not defined on the top-level resource. Specifying the path on the top-level resource has no effect, but can be used for readability purposes.Path variables
The path can contain variables that get resolved to
@Pathparameters or access through theRestRequest.getPathParams()method.Example:
@Rest ( path="/myResource/{foo}/{bar}" )public class MyResourceextends BasicRestServlet {@RestGet ("/{baz}" )public void String doX(@Path Stringfoo ,@Path int bar ,@Path MyPojobaz ) { ... } }Variables can be used on either top-level or child resources and can be defined on multiple levels.
All variables in the path must be specified or else the target will not resolve and a
404 will result.When variables are used on a path of a top-level resource deployed as a Spring bean in a Spring Boot application, the first part of the URL must be a literal which will be used as the servlet path of the registered servlet.
Notes:
-
The leading slash is optional.
"/myResource" and"myResource" is equivalent. -
The paths
"/myResource" and"/myResource/*" are equivalent. -
Paths must not end with
"/" (per the servlet spec). -
Effective only when this class is registered directly with the servlet container as a top-level
resource. When this class is imported as a mixin via
@Rest(mixins=...), the importing host's ownpath()orpaths()governs the mount and this annotation is silently ignored — mixin endpoints land in the host's URL namespace.
Inheritance Rules
- Path is searched for in child-to-parent order.
- Returns:
- The annotation value.
- Default:
- ""
-
On child resources (resource classes attached to parents via the
-
paths
Additional servlet mount paths.Optional multi-mount companion to
path()for top-level servlet deployment.When specified, servlet containers may mount this resource on each listed path. This is primarily intended for built-in support endpoints such as health probes where multiple exact URLs should be served by a single servlet instance.
Runtime substitution (since 10.0.0)
Each array element is treated as a template:
- The element runs through
REST Server SVL Variables
variable substitution (e.g.
$C{health.paths},$E{HEALTH_PATHS,/healthz},$S{my.system.prop,/healthz}) using the bootstrapVarResolveron the bean store. - The post-SVL value is split on
,; each piece is trimmed and empty pieces are dropped. A single template element can therefore expand to zero, one, or many mount paths.
Examples:
// 1. Single key resolving to a multi-value config string. @Rest (paths={"$C{health.paths}" })// 2. Mix literal + resolved element. @Rest (paths={"/api" ,"$C{extra.paths}" })// 3. Env var with comma-separated defaults baked in. @Rest (paths={"$E{HEALTH_PATHS,/healthz,/readyz}" })Notes:
- Paths are normalized to servlet path-specs by the hosting runtime.
-
When both
path()andpaths()are present, runtimes may usepaths()for top-level mounting and continue usingpath()for child-resource composition. -
The annotation default sits at the lowest rung of the runtime-override resolution chain — see
RestContext.getPaths()for the full precedence order (programmatic > getter > annotation). - An SVL failure (unresolved variable with no default) falls back to the literal element rather than throwing during construction.
-
Effective only when this class is registered directly with the servlet container as a top-level
resource. When this class is imported as a mixin via
@Rest(mixins=...), the importing host's ownpath()orpaths()governs the mount and this annotation is silently ignored — mixin endpoints land in the host's URL namespace.
- Returns:
- The annotation value.
- Default:
- {}
- The element runs through
REST Server SVL Variables
variable substitution (e.g.
-
pathParams
Default path parameter definitions.Provides default values for
@Pathannotations on method parameters across all methods in this class.Example:
@Rest ( pathParams={@Path (name="version" , def="v1" ) } )public class MyResource {...}- Returns:
- The annotation value.
- Since:
- 9.2.0
- Default:
- {}
-
produces
Supported accept media types.Overrides the media types inferred from the serializers that identify what media types can be produced by the resource.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- {}
-
Supports REST Server SVL Variables
(e.g.
-
queryParams
Default query parameter definitions.Provides default values for
@Queryannotations on method parameters across all methods in this class. Values specified here are used as defaults when the same property is not explicitly defined on a method parameter's@Queryannotation.Example:
// Define common query parameters at class level @Rest ( queryParams={@Query (name="format" , def="json" , description="Output format" ),@Query (name="verbose" , def="false" , schema=@Schema (type="boolean" )) } )public class MyResource {// Method will inherit the default query parameter definitions @RestGet public String doGet(@Query ("format" ) String format,@Query ("verbose" )boolean verbose) {...}// Can override defaults on a per-method basis @RestGet public String doGet2(@Query (name="format" , def="xml" ) String format) {...} }Notes:
- Returns:
- The annotation value.
- Since:
- 9.2.0
- Default:
- {}
-
renderResponseStackTraces
Render response stack traces in responses.Render stack traces in HTTP response bodies when errors occur.
Off by default. Besides the stack trace itself, this same setting also determines whether the
Thrownresponse header is set and whether an error whose exception type wasn't deliberately thrown by application code (i.e. not aBasicHttpExceptionor one of its subclasses) has its class name/message echoed into the error body. Leave this off in production so that an unplanned exception type (a database driver error, a file-system exception, and the like) can't incidentally leak implementation detail to the caller; turn it on only for local debugging.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
responseProcessors
Class<? extends ResponseProcessor>[] responseProcessorsResponse processors.Specifies a list of
ResponseProcessorclasses that know how to convert POJOs returned by REST methods or set viaRestResponse.setContent(Object)into appropriate HTTP responses.These processors run in order and are the extension point that turns a method's return value into the response body. The built-in
SerializedPojoProcessoris the default POJO handler — it runs the content-negotiatedserializer, so for ordinary POJO returns the effective response format is governed by serializer ordering and the requestAccept header (seeserializers()), not by this list.A custom view-renderer
ResponseProcessorinstalled here (for example a template-rendering processor contributed by a view mixin — seemergeResponseProcessorsIntoHost()) can instead claim a return value and render it directly (e.g. as HTML from a template) before serializer negotiation is reached, changing the effective response for the returns it handles.- Returns:
- The annotation value.
- Default:
- {}
-
restOpArgs
Class<? extends RestOpArg>[] restOpArgsJava REST operation method parameter resolvers.By default, the Juneau framework will automatically Java method parameters of various types (e.g.
RestRequest ,Accept ,Reader ).
This setting allows you to provide your own resolvers for your own class types that you want resolved.- Returns:
- The annotation value.
- Default:
- {}
-
roleGuard
Role guard.An expression defining if a user with the specified roles are allowed to access methods on this class.
This is a shortcut for specifying
RestOp.roleGuard()on all the REST operations on a class.Example:
@Rest ( path="/foo" , roleGuard="ROLE_ADMIN || (ROLE_READ_WRITE && ROLE_SPECIAL)" )public class MyResourceextends BasicRestServlet { ... }Notes:
-
Supports any of the following expression constructs:
"foo" - Single arguments."foo,bar,baz" - Multiple OR'ed arguments."foo | bar | baz" - Multiple OR'ed arguments, pipe syntax."foo || bar || baz" - Multiple OR'ed arguments, Java-OR syntax."fo*" - Patterns including'*' and'?' ."fo* & *oo" - Multiple AND'ed arguments, ampersand syntax."fo* && *oo" - Multiple AND'ed arguments, Java-AND syntax."fo* || (*oo || bar)" - Parenthesis.
- AND operations take precedence over OR operations (as expected).
- Whitespace is ignored.
-
null or empty expressions always match asfalse . -
If patterns are used, you must specify the list of declared roles using
rolesDeclared(). -
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports any of the following expression constructs:
-
rolesDeclared
Declared roles.A comma-delimited list of all possible user roles.
Used in conjunction with
roleGuard()is used with patterns.This is a shortcut for specifying
RestOp.rolesDeclared()on all the REST operations on a class.Example:
@Rest ( rolesDeclared="ROLE_ADMIN,ROLE_READ_WRITE,ROLE_READ_ONLY,ROLE_SPECIAL" , roleGuard="ROLE_ADMIN || (ROLE_READ_WRITE && ROLE_SPECIAL)" )public class MyResourceextends BasicRestServlet { ... }- Returns:
- The annotation value.
- Default:
- ""
-
serializers
Class<? extends Serializer>[] serializersSpecifies the serializers for POJOs into HTTP response bodies.Serializer are used to convert POJOs to HTTP response bodies.
Any of the Juneau framework serializers can be used in this setting.
The serializer selected is based on the requestAccept header matched against the values returned by the following method using a best-match algorithm:Ordering determines the default response format. A request that sends no
Accept header (or a non-specific one such as*/* , which browsers send by default) is treated as*/* and matches the first serializer in this list. That is why the default configuration (BasicUniversalConfig) lists HTML first — so a browser, or any client that omitsAccept , receives HTML rather than JSON. Order this list deliberately, and send an explicitAccept: application/json to force JSON regardless of ordering.Serializers are automatically inherited from
serializers()annotations on parent classes with the serializers on child classes prepended to the serializer group. TheSerializerSet.NoInheritclass can be used to prevent inheriting from the parent class.Example:
// Define a REST resource that can produce JSON and XML. @Rest ( serializers={ JsonParser.class , XmlParser.class } )public class MyResource { ... }The serializers can also be tailored at the method level using
RestOp.serializers()(and related annotations).For programmatic equivalents, contribute a
SerializerSetbean via@Bean(name="serializers").Inheritance Rules
- Serializers on child override those on parent class.
SerializerSet.Inheritclass can be used to inherit and augment values from parent.SerializerSet.NoInheritclass can be used to suppress inheriting from parent.- Serializers on methods take precedence over those on classes.
See Also:
- Returns:
- The annotation value.
- Default:
- {}
-
siteName
Optional site name.The site name is intended to be a title that can be applied to the entire site.
One possible use is if you want to add the same title to the top of all pages by defining a header on a common parent class like so:
@HtmlDocConfig ( header={"<h1>$RS{siteName}</h1>" ,"<h2>$RS{title}</h2>" } )Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
staticFiles
Class<? extends StaticFiles> staticFilesStatic files.Used to retrieve localized files to be served up as static files through the REST API via the following predefined methods:
BasicRestResource.getHtdoc(String, Locale).BasicRestServlet.getHtdoc(String, Locale).
The static file finder can be accessed through the following methods:
Inheritance Rules
- Static files on child are combined with those on parent class.
- Static files are are executed child-to-parent in the order they appear in the annotation.
- Returns:
- The annotation value.
- Default:
- org.apache.juneau.rest.server.staticfile.StaticFiles.Void.class
-
swagger
Provides swagger-specific metadata on this resource.Used to populate the auto-generated OPTIONS swagger documentation.
Example:
@Rest ( path="/addressBook" ,// Swagger info. swagger=@Swagger({"contact:{name:'John Smith',email:'john@smith.com'}," ,"license:{name:'Apache 2.0',url:'http://www.apache.org/licenses/LICENSE-2.0.html'}," ,"version:'2.0', ,"termsOfService:'You are on your own.'," ,"tags:[{name:'Java',description:'Java utility',externalDocs:{description:'Home page',url:'http://juneau.apache.org'}}]," ,"externalDocs:{description:'Home page',url:'http://juneau.apache.org'}" }) )See Also:
- Returns:
- The annotation value.
- Default:
- @org.apache.juneau.rest.server.Swagger
-
swaggerProvider
Class<? extends SwaggerProvider> swaggerProviderSwagger provider.- Returns:
- The annotation value.
- Default:
- org.apache.juneau.rest.server.swagger.SwaggerProvider.Void.class
-
openApiProvider
Class<? extends OpenApiProvider> openApiProviderOpenAPI 3.1 provider.Sibling of
swaggerProvider()for the OpenAPI 3.1 emission path. Defaults toOpenApiProvider.Voidwhich resolves toBasicOpenApiProviderunless the bean store provides an override.- Returns:
- The annotation value.
- Default:
- org.apache.juneau.rest.server.openapi.OpenApiProvider.Void.class
-
title
Optional servlet title.It is used to populate the Swagger title field.
Inheritance Rules
- Label is searched for in child-to-parent order.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ). -
Corresponds to the swagger field
/info/title .
- Returns:
- The annotation value.
- Default:
- {}
-
uriAuthority
Resource authority path.Overrides the authority path value for this resource and any child resources.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
uriContext
Resource context path.Overrides the context path value for this resource and any child resources.
Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
uriRelativity
URI-resolution relativity.Specifies how relative URIs should be interpreted by serializers.
See
UriRelativityfor possible values.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-
uriResolution
URI-resolution.Specifies how relative URIs should be interpreted by serializers.
See
UriResolutionfor possible values.Notes:
-
Supports REST Server SVL Variables
(e.g.
"$L{my.localized.variable}" ).
- Returns:
- The annotation value.
- Default:
- ""
-
Supports REST Server SVL Variables
(e.g.
-