悲伤的野马 · 一文搞定 pytest-html ...· 4 天前 · |
曾深爱过的沙滩裤 · org.mockito.Answers.ge ...· 4 天前 · |
任性的小马驹 · 以Windows服务方式运行Java程序· 4 天前 · |
聪明的作业本 · Vibration Test ...· 3 天前 · |
鬼畜的回锅肉 · Win10创建TLS客户端出现严重错误怎么办 ...· 1 月前 · |
安静的领带 · Chapter 4. Publishing ...· 3 月前 · |
大力的烤面包 · 3d斗罗大陆禁图 - 百度· 3 月前 · |
酒量小的水煮鱼 · 镜之Json Compare Diff | ...· 6 月前 · |
冷静的勺子 · 美国女子“嫁给”聊天机器人 ...· 6 月前 · |
bean test |
https://docs.spring.io/spring-framework/docs/5.0.2.RELEASE/kdoc-api/spring-framework/alltypes/index.html |
无聊的日记本
7 月前 |
org.springframework.web.WebApplicationInitializer to register a
DispatcherHandler
, wrapping it in a ServletHttpHandlerAdapter, and use Java-based Spring configuration.
org.springframework.web.WebApplicationInitializer to register a
DispatcherServlet
and use Java-based Spring configuration.
Implementations are required to implement:
#getRootConfigClasses()
-- for "root" application context (non-web infrastructure) configuration.
#getServletConfigClasses()
-- for
DispatcherServlet
application context (Spring MVC infrastructure) configuration.
If an application context hierarchy is not required, applications may return all configuration via
#getRootConfigClasses()
and return
null
from
#getServletConfigClasses()
.
Abstract base class for factories that can create Spring AOP Advisors given AspectJ classes from classes honoring the AspectJ 5 annotation syntax.
This class handles annotation parsing and validation functionality. It does not actually generate Spring AOP Advisors, which is deferred to subclasses.
org.springframework.web.servlet.view.feed.AbstractAtomFeedViewAbstract superclass for Atom Feed views, using the ROME package.
>
NOTE: As of Spring 4.1, this is based on the
com.rometools
variant of ROME, version 1.5. Please upgrade your build dependency.
Application-specific view classes will extend this class. The view will be held in the subclass itself, not in a template. Main entry points are the
#buildFeedMetadata
and
#buildFeedEntries
.
Thanks to Jettro Coenradie and Sergio Bossa for the original feed view prototype!
org.springframework.beans.factory.xml.AbstractBeanDefinitionParser
Abstract BeanDefinitionParser implementation providing a number of convenience methods and a
template method
that subclasses must override to provide the actual parsing logic.
Use this BeanDefinitionParser implementation when you want to parse some arbitrarily complex XML into one or more BeanDefinition. If you just want to parse some XML into a single
BeanDefinition
, you may wish to consider the simpler convenience extensions of this class, namely AbstractSingleBeanDefinitionParser and AbstractSimpleBeanDefinitionParser.
Abstract base class for bean definition readers which implement the BeanDefinitionReader interface.
Provides common properties like the bean factory to work on and the class loader to use for loading bean classes.
org.springframework.aop.framework.autoproxy.AbstractBeanFactoryAwareAdvisingPostProcessor
Extension of AbstractAutoProxyCreator which implements BeanFactoryAware, adds exposure of the original target class for each proxied bean (
AutoProxyUtils#ORIGINAL_TARGET_CLASS_ATTRIBUTE
), and participates in an externally enforced target-class mode for any given bean (
AutoProxyUtils#PRESERVE_TARGET_CLASS_ATTRIBUTE
). This post-processor is therefore aligned with AbstractAutoProxyCreator.
Convenient superclass for org.springframework.aop.framework.autoproxy.TargetSourceCreator implementations that require creating multiple instances of a prototype bean.
Uses an internal BeanFactory to manage the target instances, copying the original bean definition to this internal factory. This is necessary because the original BeanFactory will just contain the proxy instance created through auto-proxying.
Requires running in an org.springframework.beans.factory.support.AbstractBeanFactory.
org.springframework.web.context.AbstractContextLoaderInitializerConvenient base class for WebApplicationInitializer implementations that register a ContextLoaderListener in the servlet context.
The only method required to be implemented by subclasses is
#createRootApplicationContext()
, which gets invoked from
#registerContextLoaderListener(ServletContext)
.
A base abstract class to resolve method arguments annotated with
@CookieValue
. Subclasses extract the cookie value from the request.
An
@CookieValue
is a named value that is resolved from a cookie. It has a required flag and a default value to fall back on when the cookie does not exist.
A WebDataBinder may be invoked to apply type conversion to the resolved cookie value.
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTagBase tag for all data-binding aware JSP form tags.
Provides the common
path
and
id
properties. Provides sub-classes with utility methods for accessing the BindStatus of their bound value and also for
interacting
with the TagWriter.
Abstract base class for
TestExecutionListener
implementations that provide support for marking the
ApplicationContext
associated with a test as
dirty
for both test classes and test methods annotated with the DirtiesContext annotation.
The core functionality for this class was extracted from DirtiesContextTestExecutionListener in Spring Framework 4.2.
org.springframework.web.servlet.support.AbstractDispatcherServletInitializerBase class for org.springframework.web.WebApplicationInitializer implementations that register a DispatcherServlet in the servlet context.
Most applications should consider extending the Spring Java config, sub-class AbstractAnnotationConfigDispatcherServletInitializer.
org.springframework.web.servlet.view.feed.AbstractFeedViewAbstract base class for Atom and RSS Feed views, using the ROME package.
>
NOTE: As of Spring 4.1, this is based on the
com.rometools
variant of ROME, version 1.5. Please upgrade your build dependency.
Application-specific view classes will typically extend from either AbstractRssFeedView or AbstractAtomFeedView instead of from this class.
Thanks to Jettro Coenradie and Sergio Bossa for the original feed view prototype!
org.springframework.web.socket.server.support.AbstractHandshakeHandlerA base class for HandshakeHandler implementations, independent from the Servlet API.
Performs initial validation of the WebSocket handshake request - possibly rejecting it through the appropriate HTTP status code - while also allowing its subclasses to override various parts of the negotiation process (e.g. origin validation, sub-protocol negotiation, extensions negotiation, etc).
If the negotiation succeeds, the actual upgrade is delegated to a server-specific org.springframework.web.socket.server.RequestUpgradeStrategy, which will update the response as necessary and initialize the WebSocket. Currently supported servers are Jetty 9.0-9.3, Tomcat 7.0.47+ and 8.x, Undertow 1.0-1.3, GlassFish 4.1+, WebLogic 12.1.3+.
org.springframework.web.socket.sockjs.transport.handler.AbstractHttpReceivingTransportHandlerBase class for HTTP transport handlers that receive messages via HTTP POST.
org.springframework.aop.config.AbstractInterceptorDrivenBeanDefinitionDecoratorBase implementation for org.springframework.beans.factory.xml.BeanDefinitionDecorator wishing to add an org.aopalliance.intercept.MethodInterceptor to the resulting bean.
This base class controls the creation of the ProxyFactoryBean bean definition and wraps the original as an inner-bean definition for the
target
property of ProxyFactoryBean.
Chaining is correctly handled, ensuring that only one ProxyFactoryBean definition is created. If a previous org.springframework.beans.factory.xml.BeanDefinitionDecorator already created the org.springframework.aop.framework.ProxyFactoryBean then the interceptor is simply added to the existing definition.
Subclasses have only to create the
BeanDefinition
to the interceptor that they wish to add.
Abstract base test class which integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a JUnit environment.
Concrete subclasses should typically declare a class-level ContextConfiguration annotation to configure the ApplicationContext
or
.
If your test does not need to load an application context, you may choose to omit the ContextConfiguration declaration and to configure the appropriate org.springframework.test.context.TestExecutionListener manually.
The following org.springframework.test.context.TestExecutionListener are configured by default:
This class serves only as a convenience for extension.
NOTE: As of Spring Framework 4.3, this class requires JUnit 4.12 or higher.
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverterAbstract base class for Jackson based and content type independent HttpMessageConverter implementations.
Compatible with Jackson 2.9 and higher, as of Spring 5.0.
org.springframework.remoting.jaxws.AbstractJaxWsServiceExporterAbstract exporter for JAX-WS services, autodetecting annotated service beans (through the JAX-WS javax.jws.WebService annotation).
Subclasses need to implement the
#publishEndpoint
template methods for actual endpoint exposure.
A convenient base class for a
ResponseBodyAdvice
to instruct the org.springframework.http.converter.json.MappingJackson2HttpMessageConverter to serialize with JSONP formatting.
Sub-classes must specify the query parameter name(s) to check for the name of the JSONP callback function.
Sub-classes are likely to be annotated with the
@ControllerAdvice
annotation and auto-detected or otherwise must be registered directly with the
RequestMappingHandlerAdapter
and
ExceptionHandlerExceptionResolver
.
org.springframework.aop.TargetSource implementation that will lazily create a user-managed object.
Creation of the lazy target object is controlled by the user by implementing the
#createObject()
method. This
TargetSource
will invoke this method the first time the proxy is accessed.
Useful when you need to pass a reference to some dependency to an object but you don't actually want the dependency to be created until it is first used. A typical scenario for this is a connection to a remote resource.
org.springframework.http.server.reactive.AbstractListenerReadPublisher
Abstract base class for
Publisher
implementations that bridge between event-listener read APIs and Reactive Streams.
Specifically a base class for reading from the HTTP request body with Servlet 3.1 non-blocking I/O and Undertow XNIO as well as handling incoming WebSocket messages with standard Java WebSocket (JSR-356), Jetty, and Undertow.
org.springframework.http.server.reactive.AbstractListenerWriteProcessor
Abstract base class for
Processor
implementations that bridge between event-listener write APIs and Reactive Streams.
Specifically a base class for writing to the HTTP response body with Servlet 3.1 non-blocking I/O and Undertow XNIO as well for writing WebSocket messages through the Java WebSocket API (JSR-356), Jetty, and Undertow.
org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallbackAbstract PreparedStatementCallback implementation that manages a LobCreator. Typically used as inner class, with access to surrounding method arguments.
Delegates to the
setValues
template method for setting values on the PreparedStatement, using a given LobCreator for BLOB/CLOB arguments.
A usage example with org.springframework.jdbc.core.JdbcTemplate:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object LobHandler lobHandler = new DefaultLobHandler(); // reusable object jdbcTemplate.execute( "INSERT INTO imagedb (image_name, content, description) VALUES (?, ?, ?)", new AbstractLobCreatingPreparedStatementCallback(lobHandler) { protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { ps.setString(1, name); lobCreator.setBlobAsBinaryStream(ps, 2, contentStream, contentLength); lobCreator.setClobAsString(ps, 3, description); } } );
org.springframework.jdbc.core.support.AbstractLobStreamingResultSetExtractor
Abstract ResultSetExtractor implementation that assumes streaming of LOB data. Typically used as inner class, with access to surrounding method arguments.
Delegates to the
streamData
template method for streaming LOB content to some OutputStream, typically using a LobHandler. Converts an IOException thrown during streaming to a LobRetrievalFailureException.
A usage example with JdbcTemplate:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object final LobHandler lobHandler = new DefaultLobHandler(); // reusable object jdbcTemplate.query( "SELECT content FROM imagedb WHERE image_name=?", new Object[] {name}, new AbstractLobStreamingResultSetExtractor() { public void streamData(ResultSet rs) throws SQLException, IOException { FileCopyUtils.copy(lobHandler.getBlobAsBinaryStream(rs, 1), contentStream); } } );
org.springframework.web.servlet.i18n.AbstractLocaleContextResolver
Abstract base class for LocaleContextResolver implementations. Provides support for a default locale and a default time zone.
Also provides pre-implemented versions of
#resolveLocale
and
#setLocale
, delegating to
#resolveLocaleContext
and
#setLocaleContext
.
Provides essential configuration for handling messages with simple messaging protocols such as STOMP.
#clientInboundChannel()
and
#clientOutboundChannel()
deliver messages to and from remote clients to several message handlers such as
#simpAnnotationMethodMessageHandler()
#simpleBrokerMessageHandler()
#stompBrokerRelayMessageHandler()
#userDestinationMessageHandler()
#brokerChannel()
delivers messages from within the application to the the respective message handlers.
#brokerMessagingTemplate()
can be injected into any application component to send messages.
Subclasses are responsible for the part of the configuration that feed messages to and from the client inbound/outbound channels (e.g. STOMP over WebSocket).
org.springframework.web.reactive.result.method.annotation.AbstractMessageWriterResultHandlerAbstract base class for result handlers that handle return values by writing to the response with HttpMessageWriter.
org.springframework.messaging.handler.invocation.AbstractMethodMessageHandlerAbstract base class for HandlerMethod-based message handling. Provides most of the logic required to discover handler methods at startup, find a matching handler method at runtime for a given message and invoke it.
Also supports discovering and invoking exception handling methods to process exceptions raised during message handling.
org.springframework.messaging.handler.annotation.support.AbstractNamedValueMethodArgumentResolverAbstract base class for resolving method arguments from a named value. Message headers, and path variables are examples of named values. Each may have a name, a required flag, and a default value.
Subclasses define how to do the following:
A default value string can contain ${...} placeholders and Spring Expression Language
#{...}
expressions. For this to work a ConfigurableBeanFactory must be supplied to the class constructor.
A ConversionService may be used to apply type conversion to the resolved argument value if it doesn't match the method parameter type.
org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolverAbstract base class for resolving method arguments from a named value. Request parameters, request headers, and path variables are examples of named values. Each may have a name, a required flag, and a default value.
Subclasses define how to do the following:
A default value string can contain ${...} placeholders and Spring Expression Language #{...} expressions. For this to work a ConfigurableBeanFactory must be supplied to the class constructor.
A WebDataBinder is created to apply type conversion to the resolved argument value if it doesn't match the method parameter type.
org.springframework.web.servlet.view.document.AbstractPdfStamperViewAbstract superclass for PDF views that operate on an existing document with an AcroForm. Application-specific view classes will extend this class to merge the PDF form with model data.
This view implementation uses Bruno Lowagie's iText package. Known to work with iText 2.1.7 as well as its fork OpenPDF .
Thanks to Bryant Larsen for the suggestion and the original prototype!
org.springframework.web.servlet.view.document.AbstractPdfViewAbstract superclass for PDF views. Application-specific view classes will extend this class. The view will be held in the subclass itself, not in a template.
This view implementation uses Bruno Lowagie's iText package. Known to work with iText 2.1.7 as well as its fork OpenPDF .
Note: Internet Explorer requires a ".pdf" extension, as it doesn't always respect the declared content type.
org.springframework.web.server.adapter.AbstractReactiveWebInitializerBase class for a org.springframework.web.WebApplicationInitializer that installs a Spring Reactive Web Application on a Servlet container.
Spring configuration is loaded and given to
WebHttpHandlerBuilder
which scans the context looking for specific beans and creates a reactive HttpHandler. The resulting handler is installed as a Servlet through the ServletHttpHandlerAdapter.
Abstract org.springframework.aop.TargetSource implementation that wraps a refreshable target object. Subclasses can determine whether a refresh is required, and need to provide fresh target objects.
Implements the Refreshable interface in order to allow for explicit control over the refresh status.
org.springframework.aop.support.AbstractRegexpMethodPointcutAbstract base regular expression pointcut bean. JavaBean properties are:
Note: the regular expressions must be a match. For example,
.*get.*
will match com.mycom.Foo.getBar().
get.*
will not.
This base class is serializable. Subclasses should declare all fields transient; the
#initPatternRepresentation
method will be invoked again on deserialization.
Abstract superclass for RSS Feed views, using the ROME package.
>
NOTE: As of Spring 4.1, this is based on the
com.rometools
variant of ROME, version 1.5. Please upgrade your build dependency.
Application-specific view classes will extend this class. The view will be held in the subclass itself, not in a template. Main entry points are the
#buildFeedMetadata
and
#buildFeedItems
.
Thanks to Jettro Coenradie and Sergio Bossa for the original feed view prototype!
org.springframework.beans.factory.xml.AbstractSimpleBeanDefinitionParserConvenient base class for when there exists a one-to-one mapping between attribute names on the element that is to be parsed and the property names on the Class being configured.
Extend this parser class when you want to create a single bean definition from a relatively simple custom XML element. The resulting
BeanDefinition
will be automatically registered with the relevant org.springframework.beans.factory.support.BeanDefinitionRegistry.
An example will hopefully make the use of this particular parser class immediately clear. Consider the following class definition:
public class SimpleCache implements Cache { public void setName(String name) {...} public void setTimeout(int timeout) {...} public void setEvictionPolicy(EvictionPolicy policy) {...} // remaining class definition elided for clarity... }
Then let us assume the following XML tag has been defined to permit the easy configuration of instances of the above class;
<caching:cache name="..." timeout="..." eviction-policy="..."/>
All that is required of the Java developer tasked with writing the parser to parse the above XML tag into an actual
SimpleCache
bean definition is the following:
public class SimpleCacheBeanDefinitionParser extends AbstractSimpleBeanDefinitionParser { protected Class getBeanClass(Element element) { return SimpleCache.class; } }
Please note that the
AbstractSimpleBeanDefinitionParser
is limited to populating the created bean definition with property values. if you want to parse constructor arguments and nested elements from the supplied XML element, then you will have to implement the
#postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.w3c.dom.Element)
method and do such parsing yourself, or (more likely) subclass the AbstractSingleBeanDefinitionParser or AbstractBeanDefinitionParser classes directly.
The process of actually registering the
SimpleCacheBeanDefinitionParser
with the Spring XML parsing infrastructure is described in the Spring Framework reference documentation (in one of the appendices).
For an example of this parser in action (so to speak), do look at the source code for the org.springframework.beans.factory.xml.UtilNamespaceHandler.PropertiesBeanDefinitionParser; the observant (and even not so observant) reader will immediately notice that there is next to no code in the implementation. The
PropertiesBeanDefinitionParser
populates a org.springframework.beans.factory.config.PropertiesFactoryBean from an XML element that looks like this:
<util:properties location="jdbc.properties"/>
The observant reader will notice that the sole attribute on the
<util:properties/>
element matches the
org.springframework.beans.factory.config.PropertiesFactoryBean#setLocation(org.springframework.core.io.Resource)
method name on the
PropertiesFactoryBean
(the general usage thus illustrated holds true for any number of attributes). All that the
PropertiesBeanDefinitionParser
needs actually do is supply an implementation of the
#getBeanClass(org.w3c.dom.Element)
method to return the
PropertiesFactoryBean
type.
Base class for those BeanDefinitionParser implementations that need to parse and define just a
single
BeanDefinition
.
Extend this parser class when you want to create a single bean definition from an arbitrarily complex XML element. You may wish to consider extending the AbstractSimpleBeanDefinitionParser when you want to create a single bean definition from a relatively simple custom XML element.
The resulting
BeanDefinition
will be automatically registered with the org.springframework.beans.factory.support.BeanDefinitionRegistry. Your job simply is to
parse
the custom XML Element into a single
BeanDefinition
.
Convenient superclass for FactoryBean types that produce singleton-scoped proxy objects.
Manages pre- and post-interceptors (references, rather than interceptor names, as in ProxyFactoryBean) and provides consistent interface management.
org.springframework.web.socket.sockjs.support.AbstractSockJsService
An abstract base class for SockJsService implementations that provides SockJS path resolution and handling of static SockJS requests (e.g. "/info", "/iframe.html", etc). Sub-classes must handle session URLs (i.e. transport-specific requests). By default, only same origin requests are allowed. Use
#setAllowedOrigins
to specify a list of allowed origins (a list containing "*" will allow all origins).
Abstract implementation of the SqlTypeValue interface, for convenient creation of type values that are supposed to be passed into the
PreparedStatement.setObject
method. The
createTypeValue
callback method has access to the underlying Connection, if that should be needed to create any database-specific objects.
A usage example from a StoredProcedure (compare this to the plain SqlTypeValue version in the superclass javadoc):
proc.declareParameter(new SqlParameter("myarray", Types.ARRAY, "NUMBERS")); ... Map<String, Object> in = new HashMap<String, Object>(); in.put("myarray", new AbstractSqlTypeValue() { public Object createTypeValue(Connection con, int sqlType, String typeName) throws SQLException { oracle.sql.ArrayDescriptor desc = new oracle.sql.ArrayDescriptor(typeName, con); return new oracle.sql.ARRAY(desc, con, seats); } }); Map out = execute(in);
org.springframework.web.servlet.view.AbstractTemplateViewResolver
Abstract base class for template view resolvers, in particular for FreeMarker views.
Provides a convenient way to specify AbstractTemplateView's exposure flags for request attributes, session attributes, and Spring's macro helpers.
org.springframework.test.context.testng.AbstractTestNGSpringContextTestsAbstract base test class which integrates the Spring TestContext Framework with explicit ApplicationContext testing support in a TestNG environment.
Concrete subclasses:
@ContextConfiguration
declaration and to configure the appropriate org.springframework.test.context.TestExecutionListener manually.
super();
.
The following org.springframework.test.context.TestExecutionListener are configured by default:
Base
MethodInterceptor
implementation for tracing.
By default, log messages are written to the log for the interceptor class, not the class which is being intercepted. Setting the
useDynamicLogger
bean property to
true
causes all log messages to be written to the
Log
for the target class being intercepted.
Subclasses must implement the
invokeUnderTrace
method, which is invoked by this class ONLY when a particular invocation SHOULD be traced. Subclasses should write to the
Log
instance provided.
Abstract Transactional extension of AbstractJUnit4SpringContextTests which adds convenience functionality for JDBC access. Expects a DataSource bean and a PlatformTransactionManager bean to be defined in the Spring ApplicationContext.
This class exposes a JdbcTemplate and provides an easy way to count the number of rows in a table (potentially with a WHERE clause ), delete from tables , drop tables , and execute SQL scripts within a transaction.
Concrete subclasses must fulfill the same requirements outlined in AbstractJUnit4SpringContextTests.
The following org.springframework.test.context.TestExecutionListener are configured by default:
This class serves only as a convenience for extension.
NOTE: As of Spring Framework 4.3, this class requires JUnit 4.12 or higher.
org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTestsAbstract Transactional extension of AbstractTestNGSpringContextTests which adds convenience functionality for JDBC access. Expects a DataSource bean and a PlatformTransactionManager bean to be defined in the Spring ApplicationContext.
This class exposes a JdbcTemplate and provides an easy way to count the number of rows in a table (potentially with a WHERE clause ), delete from tables , drop tables , and execute SQL scripts within a transaction.
Concrete subclasses must fulfill the same requirements outlined in AbstractTestNGSpringContextTests.
The following org.springframework.test.context.TestExecutionListener are configured by default:
Type filter that is aware of traversing over hierarchy.
This filter is useful when matching needs to be made based on potentially the whole class/interface hierarchy. The algorithm employed uses a succeed-fast strategy: if at any time a match is declared, no further processing is carried out.
org.springframework.web.socket.server.standard.AbstractTyrusRequestUpgradeStrategy
A base class for
RequestUpgradeStrategy
implementations on top of JSR-356 based servers which include Tyrus as their WebSocket engine.
Works with Tyrus 1.11 (WebLogic 12.2.1) and Tyrus 1.12 (GlassFish 4.1.1).
org.springframework.web.servlet.resource.AbstractVersionStrategyAbstract base class for VersionStrategy implementations.
Supports versions as:
Note: This base class does not provide support for generating the version string.
org.springframework.web.method.annotation.AbstractWebArgumentResolverAdapterAn abstract base class adapting a WebArgumentResolver to the HandlerMethodArgumentResolver contract.
Note:
This class is provided for backwards compatibility. However it is recommended to re-write a
WebArgumentResolver
as
HandlerMethodArgumentResolver
. Since
#supportsParameter
can only be implemented by actually resolving the value and then checking the result is not
WebArgumentResolver#UNRESOLVED
any exceptions raised must be absorbed and ignored since it's not clear whether the adapter doesn't support the parameter or whether it failed for an internal reason. The
HandlerMethodArgumentResolver
contract also provides access to model attributes and to
WebDataBinderFactory
(for type conversion).
A convenient abstract base class for WebSocketMessageBrokerConfigurer implementations providing empty method implementations for optional methods.
org.springframework.web.servlet.view.document.AbstractXlsxStreamingViewConvenient superclass for Excel document views in the Office 2007 XLSX format, using POI's streaming variant. Compatible with Apache POI 3.9 and higher.
For working with the workbook in subclasses, see Apache's POI site .
org.springframework.context.support.AbstractXmlApplicationContextConvenient base class for org.springframework.context.ApplicationContext implementations, drawing configuration from XML documents containing bean definitions understood by an org.springframework.beans.factory.xml.XmlBeanDefinitionReader.
Subclasses just have to implement the
#getConfigResources
and/or the
#getConfigLocations
method. Furthermore, they might override the
#getResourceByPath
hook to interpret relative paths in an environment-specific fashion, and/or
#getResourcePatternResolver
for extended pattern resolution.
LocaleResolver implementation that simply uses the primary locale specified in the "accept-language" header of the HTTP request (that is, the locale sent by the client browser, normally that of the client's OS).
Note: Does not support
setLocale
, since the accept header can only be changed through changing the client's locale settings.
JobFactory implementation that supports java.lang.Runnable objects as well as standard Quartz org.quartz.Job instances.
Compatible with Quartz 2.1.4 and higher, as of Spring 4.1.
org.springframework.aop.framework.adapter.AdvisorAdapterInterface allowing extension to the Spring AOP framework to allow handling of new Advisors and Advice types.
Implementing objects can create AOP Alliance Interceptors from custom advice types, enabling these advice types to be used in the Spring AOP framework, which uses interception under the covers.
There is no need for most Spring users to implement this interface; do so only if you need to introduce more Advisor or Advice types to Spring.
org.springframework.aop.framework.adapter.AdvisorAdapterRegistrationManagerBeanPostProcessor that registers AdvisorAdapter beans in the BeanFactory with an AdvisorAdapterRegistry (by default the GlobalAdvisorAdapterRegistry).
The only requirement for it to work is that it needs to be defined in application context along with "non-native" Spring AdvisorAdapters that need to be "recognized" by Spring's AOP framework.
Test annotation which indicates that the annotated
void
method should be executed
after
a transaction is ended for a test method configured to run within a transaction via Spring's
@Transactional
annotation.
As of Spring Framework 4.3,
@AfterTransaction
may be declared on Java 8 based interface default methods.
@AfterTransaction
methods declared in superclasses or as interface default methods will be executed after those of the current test class.
As of Spring Framework 4.0, this annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.core.annotation.AnnotatedElementUtilsGeneral utility methods for finding annotations, meta-annotations, and repeatable annotations on AnnotatedElement.
AnnotatedElementUtils
defines the public API for Spring's meta-annotation programming model with support for
annotation attribute overrides
. If you do not need support for annotation attribute overrides, consider using AnnotationUtils instead.
Note that the features of this class are not provided by the JDK's introspection facilities themselves.
Annotation Attribute Overrides
Support for meta-annotations with
attribute overrides
in
composed annotations
is provided by all variants of the
getMergedAnnotationAttributes()
,
getMergedAnnotation()
,
getAllMergedAnnotations()
,
getMergedRepeatableAnnotations()
,
findMergedAnnotationAttributes()
,
findMergedAnnotation()
,
findAllMergedAnnotations()
, and
findMergedRepeatableAnnotations()
methods.
The search algorithms used by methods in this class follow either find or get semantics. Consult the javadocs for each individual method for details on which search algorithm is used.
Get semantics
are limited to searching for annotations that are either
present
on an
AnnotatedElement
(i.e., declared locally or java.lang.annotation.Inherited) or declared within the annotation hierarchy
above
the
AnnotatedElement
.
Find semantics are much more exhaustive, providing get semantics plus support for the following:
@Inherited
Methods following
get semantics
will honor the contract of Java's java.lang.annotation.Inherited annotation except that locally declared annotations (including custom composed annotations) will be favored over inherited annotations. In contrast, methods following
find semantics
will completely ignore the presence of
@Inherited
since the
find
search algorithm manually traverses type and method hierarchies and thereby implicitly supports annotation inheritance without the need for
@Inherited
.
A WebSocket connection manager that is given a URI, a javax.websocket.ClientEndpoint-annotated endpoint, connects to a WebSocket server through the
#start()
and
#stop()
methods. If
#setAutoStartup(boolean)
is set to
true
this will be done automatically when the Spring ApplicationContext is refreshed.
Extension of the org.springframework.beans.factory.support.GenericBeanDefinition class, adding support for annotation metadata exposed through the AnnotatedBeanDefinition interface.
This GenericBeanDefinition variant is mainly useful for testing code that expects to operate on an AnnotatedBeanDefinition, for example strategy implementations in Spring's component scanning support (where the default definition class is org.springframework.context.annotation.ScannedGenericBeanDefinition, which also implements the AnnotatedBeanDefinition interface).
org.springframework.scheduling.annotation.AnnotationAsyncExecutionInterceptor
Specialization of AsyncExecutionInterceptor that delegates method execution to an
Executor
based on the Async annotation. Specifically designed to support use of
Async#value()
executor qualification mechanism introduced in Spring 3.1.2. Supports detecting qualifier metadata via
@Async
at the method or declaring class level. See
#getExecutorQualifier(Method)
for details.
AspectJAwareAdvisorAutoProxyCreator subclass that processes all AspectJ annotation aspects in the current application context, as well as Spring Advisors.
Any AspectJ annotated classes will automatically be recognized, and their advice applied if Spring AOP's proxy-based model is capable of applying it. This covers method execution joinpoints.
If the <aop:include> element is used, only @AspectJ beans with names matched by an include pattern will be considered as defining aspects to use for Spring auto-proxying.
Processing of Spring Advisors follows the rules established in org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.
org.springframework.context.annotation.AnnotationBeanNameGeneratororg.springframework.beans.factory.support.BeanNameGenerator implementation for bean classes annotated with the org.springframework.stereotype.Component annotation or with another annotation that is itself annotated with org.springframework.stereotype.Component as a meta-annotation. For example, Spring's stereotype annotations (such as org.springframework.stereotype.Repository) are themselves annotated with org.springframework.stereotype.Component.
Also supports Java EE 6's javax.annotation.ManagedBean and JSR-330's javax.inject.Named annotations, if available. Note that Spring component annotations always override such standard annotations.
If the annotation's value doesn't indicate a bean name, an appropriate name will be built based on the short name of the class (with the first letter lower-cased). For example:
com.xyz.FooServiceImpl -> fooServiceImpl
org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver
org.springframework.beans.factory.wiring.BeanWiringInfoResolver that uses the Configurable annotation to identify which classes need autowiring. The bean name to look up will be taken from the Configurable annotation if specified; otherwise the default will be the fully-qualified name of the class being configured.
org.springframework.cache.annotation.AnnotationCacheOperationSourceImplementation of the org.springframework.cache.interceptor.CacheOperationSource interface for working with caching metadata in annotation format.
This class reads Spring's Cacheable, CachePut and CacheEvict annotations and exposes corresponding caching operation definition to Spring's cache infrastructure. This class may also serve as base class for a custom
CacheOperationSource
.
Concrete implementation of AbstractGenericContextLoader that loads bean definitions from annotated classes.
See the Javadoc for org.springframework.test.context.ContextConfiguration for a definition of annotated class .
Note:
AnnotationConfigContextLoader
supports
annotated classes
rather than the String-based resource locations defined by the legacy org.springframework.test.context.ContextLoader API. Thus, although
AnnotationConfigContextLoader
extends
AbstractGenericContextLoader
,
AnnotationConfigContextLoader
does
not
support any String-based methods defined by
AbstractContextLoader
or
AbstractGenericContextLoader
. Consequently,
AnnotationConfigContextLoader
should chiefly be considered a org.springframework.test.context.SmartContextLoader rather than a org.springframework.test.context.ContextLoader.
org.springframework.web.context.WebApplicationContext implementation which accepts annotated classes as input - in particular org.springframework.context.annotation.Configuration-annotated classes, but also plain org.springframework.stereotype.Component classes and JSR-330 compliant classes using
javax.inject
annotations. Allows for registering classes one by one (specifying class names as config location) as well as for classpath scanning (specifying base packages as config location).
This is essentially the equivalent of org.springframework.context.annotation.AnnotationConfigApplicationContext for a web environment.
To make use of this application context, the "contextClass" context-param for ContextLoader and/or "contextClass" init-param for FrameworkServlet must be set to the fully-qualified name of this class.
As of Spring 3.1, this class may also be directly instantiated and injected into Spring's
DispatcherServlet
or
ContextLoaderListener
when using the new org.springframework.web.WebApplicationInitializer code-based alternative to
web.xml
. See its Javadoc for details and usage examples.
Unlike XmlWebApplicationContext, no default configuration class locations are assumed. Rather, it is a requirement to set the
"contextConfigLocation"
context-param for ContextLoader and/or "contextConfigLocation" init-param for FrameworkServlet. The param-value may contain both fully-qualified class names and base packages to scan for components. See
#loadBeanDefinitions
for exact details on how these locations are processed.
As an alternative to setting the "contextConfigLocation" parameter, users may implement an org.springframework.context.ApplicationContextInitializer and set the
"contextInitializerClasses"
context-param / init-param. In such cases, users should favor the
#refresh()
and
#scan(String...)
methods over the
#setConfigLocation(String)
method, which is primarily for use by
ContextLoader
.
Note: In case of multiple
@Configuration
classes, later
@Bean
definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra Configuration class.
Concrete implementation of AbstractGenericWebContextLoader that loads bean definitions from annotated classes.
See the Javadoc for org.springframework.test.context.ContextConfiguration for a definition of annotated class .
Note:
AnnotationConfigWebContextLoader
supports
annotated classes
rather than the String-based resource locations defined by the legacy org.springframework.test.context.ContextLoader API. Thus, although
AnnotationConfigWebContextLoader
extends
AbstractGenericWebContextLoader
,
AnnotationConfigWebContextLoader
does
not
support any String-based methods defined by org.springframework.test.context.support.AbstractContextLoader or
AbstractGenericWebContextLoader
. Consequently,
AnnotationConfigWebContextLoader
should chiefly be considered a org.springframework.test.context.SmartContextLoader rather than a org.springframework.test.context.ContextLoader.
A sub-class of AbstractExceptionHandlerMethodResolver that looks for MessageExceptionHandler-annotated methods in a given class. The actual exception types handled are extracted either from the annotation, if present, or from the method signature as a fallback option.
org.springframework.context.annotation.AnnotationScopeMetadataResolverA ScopeMetadataResolver implementation that by default checks for the presence of Spring's Scope annotation on the bean class.
The exact type of annotation that is checked for is configurable via
#setScopeAnnotationType(Class)
.
Implementation of the org.springframework.transaction.interceptor.TransactionAttributeSource interface for working with transaction metadata in JDK 1.5+ annotation format.
This class reads Spring's JDK 1.5+ Transactional annotation and exposes corresponding transaction attributes to Spring's transaction infrastructure. Also supports JTA 1.2's javax.transaction.Transactional and EJB3's javax.ejb.TransactionAttribute annotation (if present). This class may also serve as base class for a custom TransactionAttributeSource, or get customized through TransactionAnnotationParser strategies.
org.springframework.aop.config.AopConfigUtilsUtility class for handling registration of AOP auto-proxy creators.
Only a single auto-proxy creator can be registered yet multiple concrete implementations are available. Therefore this class wraps a simple escalation protocol, allowing classes to request a particular auto-proxy creator and know that class,
or a subclass thereof
, will eventually be resident in the application context.
Class containing static methods used to obtain information about the current AOP invocation.
The
currentProxy()
method is usable if the AOP framework is configured to expose the current proxy (not the default). It returns the AOP proxy in use. Target objects or advice can use this to make advised calls, in the same way as
getEJBObject()
can be used in EJBs. They can also use it to find advice configuration.
Spring's AOP framework does not expose proxies by default, as there is a performance cost in doing so.
The functionality in this class might be used by a target object that needed access to resources on the invocation. However, this approach should not be used when there is a reasonable alternative, as it makes application code dependent on usage under AOP and the Spring AOP framework in particular.
org.springframework.aop.config.AopNamespaceHandler
NamespaceHandler
for the
aop
namespace.
Provides a org.springframework.beans.factory.xml.BeanDefinitionParser for the
<aop:config>
tag. A
config
tag can include nested
pointcut
,
advisor
and
aspect
tags.
The
pointcut
tag allows for creation of named AspectJExpressionPointcut beans using a simple syntax:
<aop:pointcut id="getNameCalls" expression="execution(* *..ITestBean.getName(..))"/>
Using the
advisor
tag you can configure an org.springframework.aop.Advisor and have it applied to all relevant beans in you org.springframework.beans.factory.BeanFactory automatically. The
advisor
tag supports both in-line and referenced org.springframework.aop.Pointcut:
<aop:advisor id="getAgeAdvisor" pointcut="execution(* *..ITestBean.getAge(..))" advice-ref="getAgeCounter"/> <aop:advisor id="getNameAdvisor" pointcut-ref="getNameCalls" advice-ref="getNameCounter"/>
org.springframework.aop.config.AopNamespaceUtils
Utility class for handling registration of auto-proxy creators used internally by the '
aop
' namespace tags.
Only a single auto-proxy creator can be registered and multiple tags may wish to register different concrete implementations. As such this class delegates to AopConfigUtils which wraps a simple escalation protocol. Therefore classes may request a particular auto-proxy creator and know that class, or a subclass thereof , will eventually be resident in the application context.
Utility methods for AOP support code.
Mainly for internal use within Spring's AOP support.
See org.springframework.aop.framework.AopProxyUtils for a collection of framework-specific AOP utility methods which depend on internals of Spring's AOP framework implementation.
org.springframework.web.reactive.resource.AppCacheManifestTransformerA ResourceTransformer HTML5 AppCache manifests.
This transformer:
ResourceResolver
strategies
All files with an ".appcache" file extension (or the extension given to the constructor) will be transformed by this class. The hash is computed using the content of the appcache manifest so that changes in the manifest should invalidate the browser cache. This should also work with changes in referenced resources whose links are also versioned.
org.springframework.web.servlet.resource.AppCacheManifestTransformerA ResourceTransformer implementation that helps handling resources within HTML5 AppCache manifests for HTML5 offline applications.
This transformer:
ResourceResolver
strategies
All files that have the ".appcache" file extension, or the extension given in the constructor, will be transformed by this class. This hash is computed using the content of the appcache manifest and the content of the linked resources; so changing a resource linked in the manifest or the manifest itself should invalidate the browser cache.
In order to serve manifest files with the proper
"text/manifest"
content type, it is required to configure it with
contentNegotiationConfigurer.mediaType("appcache", MediaType.valueOf("text/manifest")
in a
WebMvcConfigurer
.
GenericApplicationListener adapter that delegates the processing of an event to an EventListener annotated method.
Delegates to
#processEvent(ApplicationEvent)
to give sub-classes a chance to deviate from the default. Unwraps the content of a PayloadApplicationEvent if necessary to allow method declaration to define any arbitrary event type. If a condition is defined, it is evaluated prior to invoking the underlying method.
Convenient superclass for application objects that want to be aware of the application context, e.g. for custom lookup of collaborating beans or for context-specific resource access. It saves the application context reference and provides an initialization callback method. Furthermore, it offers numerous convenience methods for message lookup.
There is no requirement to subclass this class: It just makes things a little easier if you need access to the context, e.g. for access to file resources or to the message source. Note that many application objects do not need to be aware of the application context at all, as they can receive collaborating beans via bean references.
Many framework classes are derived from this class, particularly within the web support.
org.springframework.web.context.annotation.ApplicationScope
@ApplicationScope
is a specialization of Scope for a component whose lifecycle is bound to the current web application.
Specifically,
@ApplicationScope
is a
composed annotation
that acts as a shortcut for
@Scope("application")
with the default
#proxyMode
set to
TARGET_CLASS
.
@ApplicationScope
may be used as a meta-annotation to create custom composed annotations.
Subclass of MethodInvoker that tries to convert the given arguments for the actual target method via a TypeConverter.
Supports flexible argument conversions, in particular for invoking a specific overloaded method.
org.springframework.web.servlet.tags.ArgumentTag
The
<argument>
tag is based on the JSTL
fmt:param
tag. The purpose is to support arguments inside the message and theme tags.
This tag must be nested under an argument aware tag.
Attribute Summary Attribute Required? Runtime Expression? Description value false true The value of the argument. org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer
ParameterNameDiscoverer implementation that tries to deduce parameter names for an advice method from the pointcut expression, returning, and throwing clauses. If an unambiguous interpretation is not available, it returns
null
.
This class interprets arguments in the following way:
thisJoinPoint
to the advice, and the parameter name will be assigned the value
"thisJoinPoint"
.
JoinPoint.StaticPart
, it is assumed to be for passing
"thisJoinPointStaticPart"
to the advice, and the parameter name will be assigned the value
"thisJoinPointStaticPart"
.
throwingName
has been set, and there are no unbound arguments of type
Throwable+
, then an IllegalArgumentException is raised. If there is more than one unbound argument of type
Throwable+
, then an AmbiguousBindingException is raised. If there is exactly one unbound argument of type
Throwable+
, then the corresponding parameter name is assigned the value <throwingName>.
a
be the number of annotation-based pointcut expressions (@annotation, @this, @target, @args, @within, @withincode) that are used in binding form. Usage in binding form has itself to be deduced: if the expression inside the pointcut is a single string literal that meets Java variable name conventions it is assumed to be a variable name. If
a
is zero we proceed to the next stage. If
a
> 1 then an
AmbiguousBindingException
is raised. If
a
== 1, and there are no unbound arguments of type
Annotation+
, then an
IllegalArgumentException
is raised. if there is exactly one such argument, then the corresponding parameter name is assigned the value from the pointcut expression.
IllegalArgumentException
is raised. If there is more than one unbound argument then an
AmbiguousBindingException
is raised. If there is exactly one unbound argument then the corresponding parameter name is assigned the value <returningName>.
this
,
target
, and
args
pointcut expressions used in the binding form (binding forms are deduced as described for the annotation based pointcuts). If there remains more than one unbound argument of a primitive type (which can only be bound in
args
) then an
AmbiguousBindingException
is raised. If there is exactly one argument of a primitive type, then if exactly one
args
bound variable was found, we assign the corresponding parameter name the variable name. If there were no
args
bound variables found an
IllegalStateException
is raised. If there are multiple
args
bound variables, an
AmbiguousBindingException
is raised. At this point, if there remains more than one unbound argument we raise an
AmbiguousBindingException
. If there are no unbound arguments remaining, we are done. If there is exactly one unbound argument remaining, and only one candidate variable name unbound from
this
,
target
, or
args
, it is assigned as the corresponding parameter name. If there are multiple possibilities, an
AmbiguousBindingException
is raised.
The behavior on raising an
IllegalArgumentException
or
AmbiguousBindingException
is configurable to allow this discoverer to be used as part of a chain-of-responsibility. By default the condition will be logged and the
getParameterNames(..)
method will simply return
null
. If the
raiseExceptions
property is set to
true
, the conditions will be thrown as
IllegalArgumentException
and
AmbiguousBindingException
, respectively.
Was that perfectly clear? ;)
Short version: If an unambiguous binding can be deduced, then it is. If the advice requirements cannot possibly be satisfied, then
null
is returned. By setting the
raiseExceptions
property to
true
, descriptive exceptions will be thrown instead of returning
null
in the case that the parameter names cannot be discovered.
Spring org.springframework.aop.Pointcut implementation that uses the AspectJ weaver to evaluate a pointcut expression.
The pointcut expression value is an AspectJ expression. This can reference other pointcuts and use composition and other operations.
Naturally, as this is to be processed by Spring AOP's proxy-based model, only method execution pointcuts are supported.
org.springframework.aop.aspectj.AspectJWeaverMessageHandlerImplementation of AspectJ's IMessageHandler interface that routes AspectJ weaving messages through the same logging system as the regular Spring messages.
Pass the option...
-XmessageHandlerClass:org.springframework.aop.aspectj.AspectJWeaverMessageHandler
to the weaver; for example, specifying the following in a "
META-INF/aop.xml
file:
<weaver options="..."/>
Metadata for an AspectJ aspect class, with an additional Spring AOP pointcut for the per clause.
Uses AspectJ 5 AJType reflection API, enabling us to work with different AspectJ instantiation models such as "singleton", "pertarget" and "perthis".
org.springframework.util.AssertAssertion utility class that assists in validating arguments.
Useful for identifying programmer errors early and clearly at runtime.
For example, if the contract of a public method states it does not allow
null
arguments,
Assert
can be used to validate that contract. Doing this clearly indicates a contract violation when it occurs and protects the class's invariants.
Typically used to validate method arguments rather than configuration properties, to check for cases that are usually programmer errors rather than configuration errors. In contrast to configuration initialization code, there is usually no point in falling back to defaults in such methods.
This class is similar to JUnit's assertion library. If an argument value is deemed invalid, an IllegalArgumentException is thrown (typically). For example:
Assert.notNull(clazz, "The class must not be null"); Assert.isTrue(i > 0, "The value must be greater than zero");
Mainly for internal use within the framework; consider
Apache's Commons Lang
for a more comprehensive suite of
String
utilities.
Represents assignment. An alternative to calling setValue() for an expression is to use an assign.
Example: 'someNumberProperty=42'
org.springframework.scheduling.annotation.AsyncAnnotationAdvisorAdvisor that activates asynchronous method execution through the Async annotation. This annotation can be used at the method and type level in implementation classes as well as in service interfaces.
This advisor detects the EJB 3.1
javax.ejb.Asynchronous
annotation as well, treating it exactly like Spring's own
Async
. Furthermore, a custom async annotation type may get specified through the
"asyncAnnotationType"
property.
Represents the context of a client-side HTTP request execution.
Used to invoke the next interceptor in the interceptor chain, or - if the calling interceptor is last - execute the request itself.
org.springframework.aop.interceptor.AsyncExecutionAspectSupport
Base class for asynchronous method execution aspects, such as
org.springframework.scheduling.annotation.AnnotationAsyncExecutionInterceptor
or
org.springframework.scheduling.aspectj.AnnotationAsyncExecutionAspect
.
Provides support for
executor qualification
on a method-by-method basis.
AsyncExecutionAspectSupport
objects must be constructed with a default
Executor
, but each individual method may further qualify a specific
Executor
bean to be used when executing it, e.g. through an annotation attribute.
AOP Alliance
MethodInterceptor
that processes method invocations asynchronously, using a given org.springframework.core.task.AsyncTaskExecutor. Typically used with the org.springframework.scheduling.annotation.Async annotation.
In terms of target method signatures, any parameter types are supported. However, the return type is constrained to either
void
or
java.util.concurrent.Future
. In the latter case, the Future handle returned from the proxy will be an actual asynchronous Future that can be used to track the result of the asynchronous method execution. However, since the target method needs to implement the same signature, it will have to return a temporary Future handle that just passes the return value through (like Spring's org.springframework.scheduling.annotation.AsyncResult or EJB 3.1's
javax.ejb.AsyncResult
).
When the return type is
java.util.concurrent.Future
, any exception thrown during the execution can be accessed and managed by the caller. With
void
return type however, such exceptions cannot be transmitted back. In that case an AsyncUncaughtExceptionHandler can be registered to process such exceptions.
As of Spring 3.1.2 the
AnnotationAsyncExecutionInterceptor
subclass is preferred for use due to its support for executor qualification in conjunction with Spring's
@Async
annotation.
Extends
HandlerInterceptor
with a callback method invoked after the start of asynchronous request handling.
When a handler starts an asynchronous request, the DispatcherServlet exits without invoking
postHandle
and
afterCompletion
as it normally does for a synchronous request, since the result of request handling (e.g. ModelAndView) is likely not yet ready and will be produced concurrently from another thread. In such scenarios,
#afterConcurrentHandlingStarted
is invoked instead, allowing implementations to perform tasks such as cleaning up thread-bound attributes before releasing the thread to the Servlet container.
When asynchronous handling completes, the request is dispatched to the container for further processing. At this stage the
DispatcherServlet
invokes
preHandle
,
postHandle
, and
afterCompletion
. To distinguish between the initial request and the subsequent dispatch after asynchronous handling completes, interceptors can check whether the
javax.servlet.DispatcherType
of javax.servlet.ServletRequest is
"REQUEST"
or
"ASYNC"
.
Note that
HandlerInterceptor
implementations may need to do work when an async request times out or completes with a network error. For such cases the Servlet container does not dispatch and therefore the
postHandle
and
afterCompletion
methods will not be invoked. Instead, interceptors can register to track an asynchronous request through the
registerCallbackInterceptor
and
registerDeferredResultInterceptor
methods on org.springframework.web.context.request.async.WebAsyncManager. This can be done proactively on every request from
preHandle
regardless of whether async request processing will start.
A return value handler that supports async types. Such return value types need to be handled with priority so the async value can be "unwrapped".
Note:
implementing this contract is not required but it should be implemented when the handler needs to be prioritized ahead of others. For example custom (async) handlers, by default ordered after built-in handlers, should take precedence over
@ResponseBody
or
@ModelAttribute
handling, which should occur once the async value is ready. By contrast, built-in (async) handlers are already ordered ahead of sync handlers.
Callback interface for code that operates on an org.springframework.http.client.AsyncClientHttpRequest. Allows to manipulate the request headers, and write to the request body.
Used internally by the AsyncRestTemplate, but also useful for application code.
org.springframework.web.context.request.async.AsyncRequestTimeoutException
Exception to be thrown when an async request times out. Alternatively an applications can register a DeferredResultProcessingInterceptor or a CallableProcessingInterceptor to handle the timeout through the MVC Java config or the MVC XML namespace or directly through properties of the
RequestMappingHandlerAdapter
.
By default the exception will be handled as a 503 error.
org.springframework.scheduling.annotation.AsyncResult
A pass-through
Future
handle that can be used for method signatures which are declared with a
Future
return type for asynchronous execution.
As of Spring 4.1, this class implements ListenableFuture, not just plain java.util.concurrent.Future, along with the corresponding support in
@Async
processing.
As of Spring 4.2, this class also supports passing execution exceptions back to the caller.
org.springframework.http.converter.feed.AtomFeedHttpMessageConverterImplementation of org.springframework.http.converter.HttpMessageConverter that can read and write Atom feeds. Specifically, this converter can handle Feed objects from the ROME project.
>
NOTE: As of Spring 4.1, this is based on the
com.rometools
variant of ROME, version 1.5. Please upgrade your build dependency.
By default, this converter reads and writes the media type (
application/atom+xml
). This can be overridden through the
supportedMediaTypes
property.
Simple List wrapper class that allows for elements to be automatically populated as they are requested. This is particularly useful for data binding to List, allowing for elements to be created and added to the List in a "just in time" fashion.
Note: This class is not thread-safe. To create a thread-safe version, use the
java.util.Collections#synchronizedList
utility methods.
Inspired by
LazyList
from Commons Collections.
Marks a constructor, field, setter method or config method as to be autowired by Spring's dependency injection facilities.
Only one constructor (at max) of any given bean class may carry this annotation, indicating the constructor to autowire when used as a Spring bean. Such a constructor does not have to be public.
Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.
Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container. Bean property setter methods are effectively just a special case of such a general config method. Such config methods do not have to be public.
In the case of a multi-arg constructor or method, the 'required' parameter is applicable to all arguments. Individual parameters may be declared as Java-8-style java.util.Optional or, as of Spring Framework 5.0, also as
@Nullable
or a not-null parameter type in Kotlin, overriding the base required semantics.
In case of a java.util.Collection or java.util.Map dependency type, the container autowires all beans matching the declared value type. For such purposes, the map keys must be declared as type String which will be resolved to the corresponding bean names. Such a container-provided collection will be ordered, taking into account org.springframework.core.Ordered/org.springframework.core.annotation.Order values of the target components, otherwise following their registration order in the container. Alternatively, a single matching target bean may also be a generally typed
Collection
or
Map
itself, getting injected as such.
Note that actual injection is performed through a org.springframework.beans.factory.config.BeanPostProcessor which in turn means that you
cannot
use
@Autowired
to inject references into org.springframework.beans.factory.config.BeanPostProcessor or org.springframework.beans.factory.config.BeanFactoryPostProcessor types. Please consult the javadoc for the AutowiredAnnotationBeanPostProcessor class (which, by default, checks for the presence of this annotation).
org.springframework.beans.factory.config.BeanPostProcessor implementation that autowires annotated fields, setter methods and arbitrary config methods. Such members to be injected are detected through a Java 5 annotation: by default, Spring's Autowired and Value annotations.
Also supports JSR-330's javax.inject.Inject annotation, if available, as a direct alternative to Spring's own
@Autowired
.
Only one constructor (at max) of any given bean class may carry this annotation with the 'required' parameter set to
true
, indicating
the
constructor to autowire when used as a Spring bean. If multiple
non-required
constructors carry the annotation, they will be considered as candidates for autowiring. The constructor with the greatest number of dependencies that can be satisfied by matching beans in the Spring container will be chosen. If none of the candidates can be satisfied, then a default constructor (if present) will be used. An annotated constructor does not have to be public.
Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.
Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container. Bean property setter methods are effectively just a special case of such a general config method. Config methods do not have to be public.
Note: A default AutowiredAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom AutowiredAnnotationBeanPostProcessor bean definition.
NOTE: Annotation injection will be performed before XML injection; thus the latter configuration will override the former for properties wired through both approaches.
In addition to regular injection points as discussed above, this post-processor also handles Spring's Lookup annotation which identifies lookup methods to be replaced by the container at runtime. This is essentially a type-safe version of
getBean(Class, args)
and
getBean(String, args)
, See Lookup for details.
Exception thrown when SQL specified is invalid. Such exceptions always have a
java.sql.SQLException
root cause.
It would be possible to have subclasses for no such table, no such column etc. A custom SQLExceptionTranslator could create such more specific exceptions, without affecting code using this class.
org.springframework.util.Base64UtilsA simple utility class for Base64 encoding and decoding.
Adapts to Java 8's java.util.Base64 in a convenience fashion.
org.springframework.jdbc.object.BatchSqlUpdate
SqlUpdate subclass that performs batch update operations. Encapsulates queuing up records to be updated, and adds them as a single batch once
flush
is called or the given batch size has been met.
Note that this class is a
non-thread-safe object
, in contrast to all other JDBC operations objects in this package. You need to create a new instance of it for each use, or call
reset
before reuse within the same thread.
Convenient base class for bean configurers that can perform Dependency Injection on objects (however they may be created). Typically subclassed by AspectJ aspects.
Subclasses may also need a custom metadata resolution strategy, in the BeanWiringInfoResolver interface. The default implementation looks for a bean with the same name as the fully-qualified class name. (This is the default name of the bean in a Spring XML file if the '
id
' attribute is not used.)
SPI for parsing an XML document that contains Spring bean definitions. Used by XmlBeanDefinitionReader for actually parsing a DOM document.
Instantiated per document to parse: implementations can hold state in instance variables during the execution of the
registerBeanDefinitions
method — for example, global settings that are defined for all bean definitions in the document.
Extension to the standard BeanFactoryPostProcessor SPI, allowing for the registration of further bean definitions before regular BeanFactoryPostProcessor detection kicks in. In particular, BeanDefinitionRegistryPostProcessor may register further bean definitions which in turn define BeanFactoryPostProcessor instances.
org.springframework.beans.factory.config.BeanDefinitionVisitorVisitor class for traversing BeanDefinition objects, in particular the property values and constructor argument values contained in them, resolving bean metadata values.
Used by PropertyPlaceholderConfigurer to parse all String values contained in a BeanDefinition, resolving any placeholders found.
org.springframework.beans.factory.config.BeanExpressionResolverStrategy interface for resolving a value through evaluating it as an expression, if applicable.
A raw org.springframework.beans.factory.BeanFactory does not contain a default implementation of this strategy. However, org.springframework.context.ApplicationContext implementations will provide expression support out of the box.
org.springframework.jdbc.datasource.lookup.BeanFactoryDataSourceLookupDataSourceLookup implementation based on a Spring BeanFactory.
Will lookup Spring managed beans identified by bean name, expecting them to be of type
javax.sql.DataSource
.
DestinationResolver implementation based on a Spring BeanFactory.
Will lookup Spring managed beans identified by bean name, expecting them to be of type
javax.jms.Destination
.
Refreshable TargetSource that fetches fresh target beans from a BeanFactory.
Can be subclassed to override
requiresRefresh()
to suppress unnecessary refreshes. By default, a refresh will be performed every time the "refreshCheckDelay" has elapsed.
Convenience methods operating on bean factories, in particular on the ListableBeanFactory interface.
Returns bean counts, bean names or bean instances, taking into account the nesting hierarchy of a bean factory (which the methods defined on the ListableBeanFactory interface don't, in contrast to the methods defined on the BeanFactory interface).
org.springframework.beans.factory.BeanInitializationExceptionException that a bean implementation is suggested to throw if its own factory-aware initialization code fails. BeansExceptions thrown by bean factory methods themselves should simply be propagated as-is.
Note that
afterPropertiesSet()
or a custom "init-method" can throw any exception.
Auto proxy creator that identifies beans to proxy via a list of names. Checks for direct, "xxx*", and "*xxx" matches.
For configuration details, see the javadoc of the parent class AbstractAutoProxyCreator. Typically, you will specify a list of interceptor names to apply to all identified beans, via the "interceptorNames" property.
org.springframework.web.servlet.view.BeanNameViewResolver
A simple implementation of org.springframework.web.servlet.ViewResolver that interprets a view name as a bean name in the current application context, i.e. typically in the XML file of the executing
DispatcherServlet
.
This resolver can be handy for small applications, keeping all definitions ranging from controllers to views in the same place. For larger applications, XmlViewResolver will be the better choice, as it separates the XML view bean definitions into a dedicated views file.
Note: Neither this
ViewResolver
nor XmlViewResolver supports internationalization. Consider ResourceBundleViewResolver if you need to apply different view resources per locale.
Note: This
ViewResolver
implements the Ordered interface in order to allow for flexible participation in
ViewResolver
chaining. For example, some special views could be defined via this
ViewResolver
(giving it 0 as "order" value), while all remaining views could be resolved by a UrlBasedViewResolver.
RowMapper implementation that converts a row into a new instance of the specified mapped target class. The mapped target class must be a top-level class and it must have a default or no-arg constructor.
Column values are mapped based on matching the column name as obtained from result set metadata to public setters for the corresponding properties. The names are matched either directly or by transforming a name separating the parts with underscores to the same name using "camel" case.
Mapping is provided for fields in the target class for many common types, e.g.: String, boolean, Boolean, byte, Byte, short, Short, int, Integer, long, Long, float, Float, double, Double, BigDecimal,
java.util.Date
, etc.
To facilitate mapping between columns and fields that don't have matching names, try using column aliases in the SQL statement like "select fname as first_name from customer".
For 'null' values read from the database, we will attempt to call the setter, but in the case of Java primitives, this causes a TypeMismatchException. This class can be configured (using the primitivesDefaultedForNullValue property) to trap this exception and use the primitives default value. Be aware that if you use the values from the generated bean to update the database the primitive value will have been set to the primitive's default value instead of null.
Please note that this class is designed to provide convenience rather than high performance. For best performance, consider using a custom RowMapper implementation.
org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSourceSqlParameterSource implementation that obtains parameter values from bean properties of a given JavaBean object. The names of the bean properties have to match the parameter names.
Uses a Spring BeanWrapper for bean property access underneath.
org.springframework.beans.BeanUtilsStatic convenience methods for JavaBeans: for instantiating beans, checking bean property types, copying bean properties, etc.
Mainly for use within the framework, but to some degree also useful for application classes.
org.springframework.beans.factory.xml.BeansDtdResolverEntityResolver implementation for the Spring beans DTD, to load the DTD from the Spring class path (or JAR file).
Fetches "spring-beans.dtd" from the class path resource "/org/springframework/beans/factory/xml/spring-beans.dtd", no matter whether specified as some local URL that includes "spring-beans" in the DTD name or as "http://www.springframework.org/dtd/spring-beans-2.0.dtd".
Test annotation which indicates that the annotated
void
method should be executed
before
a transaction is started for a test method configured to run within a transaction via Spring's
@Transactional
annotation.
As of Spring Framework 4.3,
@BeforeTransaction
may be declared on Java 8 based interface default methods.
@BeforeTransaction
methods declared in superclasses or as interface default methods will be executed before those of the current test class.
As of Spring Framework 4.0, this annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.web.socket.handler.BinaryWebSocketHandlerA convenient base class for WebSocketHandler implementations that process binary messages only.
Text messages are rejected with
CloseStatus#NOT_ACCEPTABLE
. All other methods have empty implementations.
This
<hasBindErrors>
tag provides an Errors instance in case of bind errors. The HTML escaping flag participates in a page-wide or application-wide setting (i.e. by HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml). Attribute Summary Attribute Required? Runtime Expression? Description htmlEscape false true Set HTML escaping for this tag, as boolean value. Overrides the default HTML escaping setting for the current page. name true true The name of the bean in the request that needs to be inspected for errors. If errors are available for this bean, they will be bound under the 'errors' key.
Thrown when binding errors are considered fatal. Implements the BindingResult interface (and its super-interface Errors) to allow for the direct analysis of binding errors.
As of Spring 2.0, this is a special-purpose class. Normally, application code will work with the BindingResult interface, or with a DataBinder that in turn exposes a BindingResult via
org.springframework.validation.DataBinder#getBindingResult()
.
Simple adapter to expose the bind status of a field or object. Set as a variable by FreeMarker macros and other tag libraries.
Obviously, object status representations (i.e. errors at the object level rather than the field level) do not have an expression and a value but only error codes and messages. For simplicity's sake and to be able to use the same tags and macros, the same status class is used for both scenarios.
org.springframework.validation.support.BindingAwareConcurrentModelSubclass of ConcurrentModel that automatically removes the BindingResult object when its corresponding target attribute is replaced through regular Map operations.
This is the class exposed to handler methods by Spring WebFlux, typically consumed through a declaration of the org.springframework.ui.Model interface as a parameter type. There is typically no need to create it within user code. If necessary a handler method can return a regular
java.util.Map
, likely a
java.util.ConcurrentMap
, for a pre-determined model.
Subclass of org.springframework.ui.ExtendedModelMap that automatically removes a org.springframework.validation.BindingResult object if the corresponding target attribute gets replaced through regular Map operations.
This is the class exposed to handler methods by Spring MVC, typically consumed through a declaration of the org.springframework.ui.Model interface. There is no need to build it within user code; a plain org.springframework.ui.ModelMap or even a just a regular Map with String keys will be good enough to return a user model.
org.springframework.test.context.BootstrapWith
@BootstrapWith
defines class-level metadata that is used to determine how to bootstrap the
Spring TestContext Framework
.
This annotation may also be used as a meta-annotation to create custom composed annotations .
org.springframework.core.BridgeMethodResolver
Helper for resolving synthetic
bridge Methods
to the Method being bridged.
Given a synthetic
bridge Method
returns the Method being bridged. A bridge method may be created by the compiler when extending a parameterized type whose methods have parameterized arguments. During runtime invocation the bridge Method may be invoked and/or used via reflection. When attempting to locate annotations on Method, it is wise to check for bridge Method as appropriate and find the bridged Method.
See The Java Language Specification for more details on the use of bridge methods.
org.springframework.jms.core.BrowserCallbackCallback for browsing the messages in a JMS queue.
To be used with JmsTemplate's callback methods that take a BrowserCallback argument, often implemented as an anonymous inner class or as a lambda expression.
org.springframework.scripting.bsh.BshScriptFactoryorg.springframework.scripting.ScriptFactory implementation for a BeanShell script.
Typically used in combination with a org.springframework.scripting.support.ScriptFactoryPostProcessor; see the latter's javadoc for a configuration example.
org.springframework.http.converter.BufferedImageHttpMessageConverterImplementation of HttpMessageConverter that can read and write BufferedImage.
By default, this converter can read all media types that are supported by the
registered image readers
, and writes using the media type of the first available
registered image writer
. The latter can be overridden by setting the
defaultContentType
property.
If the
cacheDir
property is set, this converter will cache image data.
The
#process(ImageReadParam)
and
#process(ImageWriteParam)
template methods allow subclasses to override Image I/O parameters.
Wrapper for a ClientHttpRequestFactory that buffers all outgoing and incoming streams in memory.
Using this wrapper allows for multiple reads of the
org.springframework.messaging.simp.stomp.BufferingStompDecoderAn extension of org.springframework.messaging.simp.stomp.StompDecoder that buffers content remaining in the input ByteBuffer after the parent class has read all (complete) STOMP frames from it. The remaining content represents an incomplete STOMP frame. When called repeatedly with additional data, the decode method returns one or more messages or, if there is not enough data still, continues to buffer.
A single instance of this decoder can be invoked repeatedly to read all messages from a single stream (e.g. WebSocket session) as long as decoding does not fail. If there is an exception, StompDecoder instance should not be used any more as its internal state is not guaranteed to be consistent. It is expected that the underlying session is closed at that point.
org.springframework.web.servlet.tags.form.ButtonTag
The
<button>
tag renders a form field label in an HTML 'button' tag. It is provided for completeness if the application relies on a RequestDataValueProcessor.
Attribute Summary Attribute Required? Runtime Expression? Description
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
false
HTML Standard Attribute
false
The name attribute for the HTML button tag
value
false
The name attribute for the HTML button tag
org.springframework.http.converter.ByteArrayHttpMessageConverterImplementation of HttpMessageConverter that can read and write byte arrays.
By default, this converter supports all media types (
*/*
), and writes with a
Content-Type
of
application/octet-stream
. This can be overridden by setting the
supportedMediaTypes
property.
Resource implementation for a given byte array.
Creates a ByteArrayInputStream for the given byte array.
Useful for loading content from any given byte array, without having to resort to a single-use InputStreamResource. Particularly useful for creating mail attachments from local content, where JavaMail needs to be able to read the stream multiple times.
org.springframework.cache.interceptor.CacheAspectSupportBase class for caching aspects, such as the CacheInterceptor or an AspectJ aspect.
This enables the underlying Spring caching infrastructure to be used easily to implement an aspect for any aspect system.
Subclasses are responsible for calling methods in this class in the correct order.
Uses the Strategy design pattern. A CacheResolver implementation will resolve the actual cache(s) to use, and a CacheOperationSource is used for determining caching operations.
A cache aspect is serializable if its
CacheResolver
and
CacheOperationSource
are serializable.
NamespaceHandler
allowing for the configuration of declarative cache management using either XML or using annotations.
This namespace handler is the central piece of functionality in the Spring cache management facilities.
org.springframework.cache.interceptor.CacheProxyFactoryBeanProxy factory bean for simplified declarative caching handling. This is a convenient alternative to a standard AOP org.springframework.aop.framework.ProxyFactoryBean with a separate CacheInterceptor definition.
This class is designed to facilitate declarative cache demarcation: namely, wrapping a singleton target object with a caching proxy, proxying all the interfaces that the target implements. Exists primarily for third-party framework integration.
Users should favor the
cache:
XML namespace org.springframework.cache.annotation.Cacheable annotation.
See the
declarative annotation-based caching
section of the Spring reference documentation for more information.
Annotation indicating that a method (or all methods on a class) triggers a
cache put
operation.
In contrast to the Cacheable annotation, this annotation does not cause the advised method to be skipped. Rather, it always causes the method to be invoked and its result to be stored in the associated cache. Note that Java8's
Optional
return types are automatically handled and its content is stored in the cache if present.
This annotation may be used as a meta-annotation to create custom composed annotations with attribute overrides.
org.springframework.beans.CachedIntrospectionResultsInternal class that caches JavaBeans java.beans.PropertyDescriptor information for a Java class. Not intended for direct use by application code.
Necessary for own caching of descriptors within the application's ClassLoader, rather than rely on the JDK's system-wide BeanInfo cache (in order to avoid leaks on ClassLoader shutdown).
Information is cached statically, so we don't need to create new objects of this class for every JavaBean we manipulate. Hence, this class implements the factory design pattern, using a private constructor and a static
#forClass(Class)
factory method to obtain instances.
Note that for caching to work effectively, some preconditions need to be met: Prefer an arrangement where the Spring jars live in the same ClassLoader as the application classes, which allows for clean caching along with the application's lifecycle in any case. For a web application, consider declaring a local org.springframework.web.util.IntrospectorCleanupListener in
web.xml
in case of a multi-ClassLoader layout, which will allow for effective caching as well.
In case of a non-clean ClassLoader arrangement without a cleanup listener having been set up, this class will fall back to a weak-reference-based caching model that recreates much-requested entries every time the garbage collector removed them. In such a scenario, consider the
#IGNORE_BEANINFO_PROPERTY_NAME
system property.
Group annotation for multiple cache annotations (of different or the same type).
This annotation may be used as a meta-annotation to create custom composed annotations with attribute overrides.
org.springframework.cache.annotation.CachingConfigurationSelector
Selects which implementation of AbstractCachingConfiguration should be used based on the value of
EnableCaching#mode
on the importing
@Configuration
class.
Detects the presence of JSR-107 and enables JCache support accordingly.
org.springframework.jms.connection.CachingConnectionFactory
SingleConnectionFactory subclass that adds javax.jms.Session caching as well javax.jms.MessageProducer caching. This ConnectionFactory also switches the
"reconnectOnException" property
to "true" by default, allowing for automatic recovery of the underlying Connection.
By default, only one single Session will be cached, with further requested Sessions being created and disposed on demand. Consider raising the
"sessionCacheSize" value
in case of a high-concurrency environment.
When using the JMS 1.0.2 API, this ConnectionFactory will switch into queue/topic mode according to the JMS API methods used at runtime:
createQueueConnection
and
createTopicConnection
will lead to queue/topic mode, respectively; generic
createConnection
calls will lead to a JMS 1.1 connection which is able to serve both modes.
NOTE: This ConnectionFactory requires explicit closing of all Sessions obtained from its shared Connection. This is the usual recommendation for native JMS access code anyway. However, with this ConnectionFactory, its use is mandatory in order to actually allow for Session reuse.
Note also that MessageConsumers obtained from a cached Session won't get closed until the Session will eventually be removed from the pool. This may lead to semantic side effects in some cases. For a durable subscriber, the logical
Session.close()
call will also close the subscription. Re-registering a durable consumer for the same subscription on the same Session handle is not supported; close and reobtain a cached Session first.
DestinationResolver implementation that proxies a target DestinationResolver, caching its
#resolveDestination
results. Such caching is particularly useful if the destination resolving process is expensive (e.g. the destination has to be resolved through an external system) and the resolution results are stable anyway.
Spring org.springframework.cache.Cache adapter implementation on top of a Caffeine com.github.benmanes.caffeine.cache.Cache instance.
Requires Caffeine 2.1 or higher.
org.springframework.cache.caffeine.CaffeineCacheManager
CacheManager implementation that lazily builds CaffeineCache instances for each
#getCache
request. Also supports a 'static' mode where the set of cache names is pre-defined through
#setCacheNames
, with no dynamic creation of further cache regions at runtime.
The configuration of the underlying cache can be fine-tuned through a Caffeine builder or CaffeineSpec, passed into this CacheManager through
#setCaffeine
/
#setCaffeineSpec
. A CaffeineSpec-compliant expression value can also be applied via the
"cacheSpecification"
bean property.
Requires Caffeine 2.1 or higher.
org.springframework.jdbc.core.metadata.CallMetaDataProviderInterface specifying the API to be implemented by a class providing call metadata.
This is intended for internal use by Spring's org.springframework.jdbc.core.simple.SimpleJdbcCall.
org.springframework.transaction.support.CallbackPreferringPlatformTransactionManagerExtension of the org.springframework.transaction.PlatformTransactionManager interface, exposing a method for executing a given callback within a transaction.
Implementors of this interface automatically express a preference for callbacks over programmatic
getTransaction
,
commit
and
rollback
calls. Calling code may check whether a given transaction manager implements this interface to choose to prepare a callback instead of explicit transaction demarcation control.
Spring's TransactionTemplate and org.springframework.transaction.interceptor.TransactionInterceptor detect and use this PlatformTransactionManager variant automatically.
org.springframework.oxm.castor.CastorMarshaller
Implementation of the
Marshaller
interface for Castor. By default, Castor does not require any further configuration, though setting target classes, target packages or providing a mapping file can be used to have more control over the behavior of Castor.
If a target class is specified using
setTargetClass
, the
CastorMarshaller
can only be used to unmarshal XML that represents that specific class. If you want to unmarshal multiple classes, you have to provide a mapping file using
setMappingLocations
.
Due to limitations of Castor's API, it is required to set the encoding used for writing to output streams. It defaults to
UTF-8
.
XStream Converter that supports all classes, but throws exceptions for (un)marshalling.
The main purpose of this class is to register this converter as a catch-all last converter with a normal or higher priority, in addition to converters that explicitly handle the domain classes that should be supported. As a result, default XStream converters with lower priorities and possible security vulnerabilities do not get invoked.
For instance:
XStreamMarshaller unmarshaller = new XStreamMarshaller(); unmarshaller.getXStream().registerConverter(new MyDomainClassConverter(), XStream.PRIORITY_VERY_HIGH); unmarshaller.getXStream().registerConverter(new CatchAllConverter(), XStream.PRIORITY_NORMAL); MyDomainClass myObject = unmarshaller.unmarshal(source);
org.springframework.jca.cci.core.support.CciDaoSupport
Convenient super class for CCI-based data access objects.
Requires a javax.resource.cci.ConnectionFactory to be set, providing a org.springframework.jca.cci.core.CciTemplate based on it to subclasses through the
#getCciTemplate()
method.
This base class is mainly intended for CciTemplate usage but can also be used when working with a Connection directly or when using
org.springframework.jca.cci.object
classes.
org.springframework.transaction.PlatformTransactionManager implementation that manages local transactions for a single CCI ConnectionFactory. Binds a CCI Connection from the specified ConnectionFactory to the thread, potentially allowing for one thread-bound Connection per ConnectionFactory.
Application code is required to retrieve the CCI Connection via
ConnectionFactoryUtils#getConnection(ConnectionFactory)
instead of a standard Java EE-style
ConnectionFactory#getConnection()
call. Spring classes such as org.springframework.jca.cci.core.CciTemplate use this strategy implicitly. If not used in combination with this transaction manager, the ConnectionFactoryUtils lookup strategy behaves exactly like the native DataSource lookup; it can thus be used in a portable fashion.
Alternatively, you can allow application code to work with the standard Java EE lookup pattern
ConnectionFactory#getConnection()
, for example for legacy code that is not aware of Spring at all. In that case, define a TransactionAwareConnectionFactoryProxy for your target ConnectionFactory, which will automatically participate in Spring-managed transactions.
Default object instantiation strategy for use in BeanFactories.
Uses CGLIB to generate subclasses dynamically if methods need to be overridden by the container to implement Method Injection .
org.springframework.http.server.reactive.ChannelSendOperator
Given a write function that accepts a source
Publisher<T>
to write with and returns
Publisher<Void>
for the result, this operator helps to defer the invocation of the write function, until we know if the source publisher will begin publishing without an error. If the first emission is an error, the write function is bypassed, and the error is sent directly through the result publisher. Otherwise the write function is invoked.
Editor for a Character, to populate a property of type
Character
or
char
from a String value.
Note that the JDK does not contain a default java.beans.PropertyEditor for
char
! org.springframework.beans.BeanWrapperImpl will register this editor by default.
Also supports conversion from a Unicode character sequence; e.g.
u0041
('A').
Servlet Filter that allows one to specify a character encoding for requests. This is useful because current browsers typically do not set a character encoding even if specified in the HTML page or form.
This filter can either apply its encoding if the request does not already specify an encoding, or enforce this filter's encoding in any case ("forceEncoding"="true"). In the latter case, the encoding will also be applied as default response encoding (although this will usually be overridden by a full content type set in the view).
org.springframework.beans.propertyeditors.CharsetEditor
Editor for
java.nio.charset.Charset
, translating charset String representations into Charset objects and back.
Expects the same syntax as Charset's
java.nio.charset.Charset#name()
, e.g.
UTF-8
,
ISO-8859-16
, etc.
The
<checkbox>
tag renders an HTML 'input' tag with type 'checkbox'. May be used in one of three different approaches depending on the type of the
bound value
. Approach One When the bound value is of type Boolean then the '
input(checkbox)
' is marked as 'checked' if the bound value is
true
. The '
value
' attribute corresponds to the resolved value of the
value
property. Approach Two When the bound value is of type Collection then the '
input(checkbox)
' is marked as 'checked' if the configured
value
is present in the bound Collection. Approach Three For any other bound value type, the '
input(checkbox)
' is marked as 'checked' if the configured
value
is equal to the bound value.
Attribute Summary Attribute Required? Runtime Expression? Description
accesskey
false
HTML Standard Attribute
cssClass
false
HTML Optional Attribute
cssErrorClass
false
HTML Optional Attribute. Used when the bound field has errors.
cssStyle
false
HTML Optional Attribute
false
HTML Standard Attribute
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
label
false
Value to be displayed as part of the tag
false
HTML Standard Attribute
onblur
false
HTML Event Attribute
onchange
false
HTML Event Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onfocus
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
Path to property for data binding
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
value
false
HTML Optional Attribute
org.springframework.web.servlet.tags.form.CheckboxesTag
The
<checkboxes>
tag renders multiple HTML 'input' tags with type 'checkbox'. Intended to be used with a Collection as the
#getItems()
bound value.
Attribute Summary Attribute Required? Runtime Expression? Description
accesskey
false
HTML Standard Attribute
cssClass
false
HTML Optional Attribute
cssErrorClass
false
HTML Optional Attribute. Used when the bound field has errors.
cssStyle
false
HTML Optional Attribute
delimiter
false
Delimiter to use between each 'input' tag with type 'checkbox'. There is no delimiter by default.
false
HTML Standard Attribute
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
element
false
Specifies the HTML element that is used to enclose each 'input' tag with type 'checkbox'. Defaults to 'span'.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
itemLabel
false
Value to be displayed as part of the 'input' tags with type 'checkbox'
items
The Collection, Map or array of objects used to generate the 'input' tags with type 'checkbox'
itemValue
false
Name of the property mapped to 'value' attribute of the 'input' tags with type 'checkbox'
false
HTML Standard Attribute
onblur
false
HTML Event Attribute
onchange
false
HTML Event Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onfocus
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
Path to property for data binding
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
org.springframework.beans.factory.support.ChildBeanDefinitionBean definition for beans which inherit settings from their parent. Child bean definitions have a fixed dependency on a parent bean definition.
A child bean definition will inherit constructor argument values, property values and method overrides from the parent, with the option to add new values. If init method, destroy method and/or static factory method are specified, they will override the corresponding parent settings. The remaining settings will always be taken from the child definition: depends on, autowire mode, dependency check, singleton, lazy init.
NOTE:
Since Spring 2.5, the preferred way to register bean definitions programmatically is the GenericBeanDefinition class, which allows to dynamically define parent dependencies through the
GenericBeanDefinition#setParentName
method. This effectively supersedes the ChildBeanDefinition class for most use cases.
Property editor for an array of Class, to enable the direct population of a
Class[]
property without having to use a
String
class name property as bridge.
Also supports "java.lang.String[]"-style array class names, in contrast to the standard
Class#forName(String)
method.
Property editor for Class, to enable the direct population of a
Class
property without recourse to having to use a String class name property as bridge.
Also supports "java.lang.String[]"-style array class names, in contrast to the standard
Class#forName(String)
method.
A bean definition scanner that detects bean candidates on the classpath, registering corresponding bean definitions with a given registry (
BeanFactory
or
ApplicationContext
).
Candidate classes are detected through configurable type filters. The default filters include classes that are annotated with Spring's org.springframework.stereotype.Component, org.springframework.stereotype.Repository, org.springframework.stereotype.Service, or org.springframework.stereotype.Controller stereotype.
Also supports Java EE 6's javax.annotation.ManagedBean and JSR-330's javax.inject.Named annotations, if available.
org.springframework.context.support.ClassPathXmlApplicationContextStandalone XML application context, taking the context definition files from the class path, interpreting plain paths as class path resource names that include the package path (e.g. "mypackage/myresource.txt"). Useful for test harnesses as well as for application contexts embedded within JARs.
The config location defaults can be overridden via
#getConfigLocations
, Config locations can either denote concrete files like "/myfiles/context.xml" or Ant-style patterns like "/myfiles/*-context.xml" (see the org.springframework.util.AntPathMatcher javadoc for pattern details).
Note: In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra XML file.
This is a simple, one-stop shop convenience ApplicationContext. Consider using the GenericApplicationContext class in combination with an org.springframework.beans.factory.xml.XmlBeanDefinitionReader for more flexible context setup.
org.springframework.asm.ClassWriterA ClassVisitor that generates classes in bytecode form. More precisely this visitor generates a byte array conforming to the Java class file format. It can be used alone, to generate a Java class "from scratch", or with one or more ClassReader and adapter class visitor to generate a modified class from one or more existing Java classes.
org.springframework.dao.CleanupFailureDataAccessExceptionException thrown when we couldn't cleanup after a data access operation, but the actual operation went OK.
For example, this exception or a subclass might be thrown if a JDBC Connection couldn't be closed after it had been used successfully.
Note that data access code might perform resources cleanup in a finally block and therefore log cleanup failure rather than rethrow it, to keep the original data access exception, if any.
org.springframework.http.client.ClientHttpRequestInterceptorIntercepts client-side HTTP requests. Implementations of this interface can be registered with the org.springframework.web.client.RestTemplate, as to modify the outgoing ClientHttpRequest and/or the incoming ClientHttpResponse.
The main entry point for interceptors is
#intercept(HttpRequest, byte[], ClientHttpRequestExecution)
.
Represents a typed, immutable, client-side HTTP request, as executed by the ExchangeFunction. Instances of this interface can be created via static builder methods.
Note that applications are more likely to perform requests through WebClient rather than using this directly.
org.springframework.remoting.rmi.CodebaseAwareObjectInputStreamSpecial ObjectInputStream subclass that falls back to a specified codebase to load classes from if not found locally. In contrast to standard RMI conventions for dynamic class download, it is the client that determines the codebase URL here, rather than the "java.rmi.server.codebase" system property on the server.
Uses the JDK's RMIClassLoader to load classes from the specified codebase. The codebase can consist of multiple URLs, separated by spaces. Note that RMIClassLoader requires a SecurityManager to be set, like when using dynamic class download with standard RMI! (See the RMI documentation for details.)
Despite residing in the RMI package, this class is not used for RmiClientInterceptor, which uses the standard RMI infrastructure instead and thus is only able to rely on RMI's standard dynamic class download via "java.rmi.server.codebase". CodebaseAwareObjectInputStream is used by HttpInvokerClientInterceptor (see the "codebaseUrl" property there).
Thanks to Lionel Mestre for suggesting the option and providing a prototype!
org.springframework.core.CollectionFactoryFactory for collections that is aware of Java 5, Java 6, and Spring collection types.
Mainly for internal use within the framework.
org.springframework.jdbc.core.ColumnMapRowMapper
RowMapper implementation that creates a
java.util.Map
for each row, representing all columns as key-value pairs: one entry for each column, with the column name as key.
The Map implementation to use and the key to use for each column in the column Map can be customized through overriding
#createColumnMap
and
#getColumnKey
, respectively.
Note: By default, ColumnMapRowMapper will try to build a linked Map with case-insensitive keys, to preserve column order as well as allow any casing to be used for column names. This requires Commons Collections on the classpath (which will be autodetected). Else, the fallback is a standard linked HashMap, which will still preserve column order but requires the application to specify the column names in the same casing as exposed by the driver.
org.springframework.core.env.CommandLinePropertySource
Abstract base class for PropertySource implementations backed by command line arguments. The parameterized type
T
represents the underlying source of command line options. This may be as simple as a String array in the case of SimpleCommandLinePropertySource, or specific to a particular API such as JOpt's
OptionSet
in the case of JOptCommandLinePropertySource. Purpose and General Usage For use in standalone Spring-based applications, i.e. those that are bootstrapped via a traditional
main
method accepting a
String[]
of arguments from the command line. In many cases, processing command-line arguments directly within the
main
method may be sufficient, but in other cases, it may be desirable to inject arguments as values into Spring beans. It is this latter set of cases in which a
CommandLinePropertySource
becomes useful. A
CommandLinePropertySource
will typically be added to the Environment of the Spring
ApplicationContext
, at which point all command line arguments become available through the
Environment#getProperty(String)
family of methods. For example:
public static void main(String[] args) { CommandLinePropertySource clps = ...; AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment().getPropertySources().addFirst(clps); ctx.register(AppConfig.class); ctx.refresh(); }
With the bootstrap logic above, the
AppConfig
class may
@Inject
the Spring
Environment
and query it directly for properties:
@Configuration public class AppConfig { @Inject Environment env; @Bean public void DataSource dataSource() { MyVendorDataSource dataSource = new MyVendorDataSource(); dataSource.setHostname(env.getProperty("db.hostname", "localhost")); dataSource.setUsername(env.getRequiredProperty("db.username")); dataSource.setPassword(env.getRequiredProperty("db.password")); // ... return dataSource; } }
Because the
CommandLinePropertySource
was added to the
Environment
's set of MutablePropertySources using the
#addFirst
method, it has highest search precedence, meaning that while "db.hostname" and other properties may exist in other property sources such as the system environment variables, it will be chosen from the command line property source first. This is a reasonable approach given that arguments specified on the command line are naturally more specific than those specified as environment variables.
As an alternative to injecting the
Environment
, Spring's
@Value
annotation may be used to inject these properties, given that a bean has been registered, either directly or through using the
<context:property-placeholder>
element. For example:
@Component public class MyComponent { @Value("my.property:defaultVal") private String myProperty; public void getMyProperty() { return this.myProperty; } // ... }
Working with option arguments
Individual command line arguments are represented as properties through the usual
PropertySource#getProperty(String)
and
PropertySource#containsProperty(String)
methods. For example, given the following command line:
--o1=v1 --o2
'o1' and 'o2' are treated as "option arguments", and the following assertions would evaluate true:
CommandLinePropertySource ps = ... assert ps.containsProperty("o1") == true; assert ps.containsProperty("o2") == true; assert ps.containsProperty("o3") == false; assert ps.getProperty("o1").equals("v1"); assert ps.getProperty("o2").equals(""); assert ps.getProperty("o3") == null;
Note that the 'o2' option has no argument, but
getProperty("o2")
resolves to empty string (
""
) as opposed to
null
, while
getProperty("o3")
resolves to
null
because it was not specified. This behavior is consistent with the general contract to be followed by all
PropertySource
implementations.
Note also that while "--" was used in the examples above to denote an option argument, this syntax may vary across individual command line argument libraries. For example, a JOpt- or Commons CLI-based implementation may allow for single dash ("-") "short" option arguments, etc.
Working with non-option arguments
Non-option arguments are also supported through this abstraction. Any arguments supplied without an option-style prefix such as "-" or "--" are considered "non-option arguments" and available through the special
property. If multiple non-option arguments are specified, the value of this property will be a comma-delimited string containing all of the arguments. This approach ensures a simple and consistent return type (String) for all properties from a
CommandLinePropertySource
and at the same time lends itself to conversion when used in conjunction with the Spring Environment and its built-in
ConversionService
. Consider the following example:
--o1=v1 --o2=v2 /path/to/file1 /path/to/file2
In this example, "o1" and "o2" would be considered "option arguments", while the two filesystem paths qualify as "non-option arguments". As such, the following assertions will evaluate true:
CommandLinePropertySource ps = ... assert ps.containsProperty("o1") == true; assert ps.containsProperty("o2") == true; assert ps.containsProperty("nonOptionArgs") == true; assert ps.getProperty("o1").equals("v1"); assert ps.getProperty("o2").equals("v2"); assert ps.getProperty("nonOptionArgs").equals("/path/to/file1,/path/to/file2");
As mentioned above, when used in conjunction with the Spring
Environment
abstraction, this comma-delimited string may easily be converted to a String array or list:
Environment env = applicationContext.getEnvironment(); String[] nonOptionArgs = env.getProperty("nonOptionArgs", String[].class); assert nonOptionArgs[0].equals("/path/to/file1"); assert nonOptionArgs[1].equals("/path/to/file2");
The name of the special "non-option arguments" property may be customized through the
#setNonOptionArgsPropertyName(String)
method. Doing so is recommended as it gives proper semantic value to non-option arguments. For example, if filesystem paths are being specified as non-option arguments, it is likely preferable to refer to these as something like "file.locations" than the default of "nonOptionArgs":
public static void main(String[] args) { CommandLinePropertySource clps = ...; clps.setNonOptionArgsPropertyName("file.locations"); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.getEnvironment().getPropertySources().addFirst(clps); ctx.register(AppConfig.class); ctx.refresh(); }
Limitations This abstraction is not intended to expose the full power of underlying command line parsing APIs such as JOpt or Commons CLI. It's intent is rather just the opposite: to provide the simplest possible abstraction for accessing command line arguments
after
they have been parsed. So the typical case will involve fully configuring the underlying command line parsing API, parsing the
String[]
of arguments coming into the main method, and then simply providing the parsing results to an implementation of
CommandLinePropertySource
. At that point, all arguments can be considered either 'option' or 'non-option' arguments and as described above can be accessed through the normal
PropertySource
and
Environment
APIs.
org.springframework.test.annotation.Commit
@Commit
is a test annotation that is used to indicate that a
test-managed transaction
should be
committed
after the test method has completed.
Consult the class-level Javadoc for org.springframework.test.context.transaction.TransactionalTestExecutionListener for an explanation of test-managed transactions .
When declared as a class-level annotation,
@Commit
defines the default commit semantics for all test methods within the test class hierarchy. When declared as a method-level annotation,
@Commit
defines commit semantics for the specific test method, potentially overriding class-level default commit or rollback semantics.
Warning
:
@Commit
can be used as direct replacement for
@Rollback(false)
; however, it should
not
be declared alongside
@Rollback
. Declaring
@Commit
and
@Rollback
on the same test method or on the same test class is unsupported and may lead to unpredictable results.
org.springframework.beans.factory.config.BeanPostProcessor implementation that supports common Java annotations out of the box, in particular the JSR-250 annotations in the
javax.annotation
package. These common Java annotations are supported in many Java EE 5 technologies (e.g. JSF 1.2), as well as in Java 6's JAX-WS.
This post-processor includes support for the javax.annotation.PostConstruct and javax.annotation.PreDestroy annotations - as init annotation and destroy annotation, respectively - through inheriting from InitDestroyAnnotationBeanPostProcessor with pre-configured annotation types.
The central element is the javax.annotation.Resource annotation for annotation-driven injection of named beans, by default from the containing Spring BeanFactory, with only
mappedName
references resolved in JNDI. The
"alwaysUseJndiLookup" flag
enforces JNDI lookups equivalent to standard Java EE 5 resource injection for
name
references and default names as well. The target beans can be simple POJOs, with no special requirements other than the type having to match.
The JAX-WS javax.xml.ws.WebServiceRef annotation is supported too, analogous to javax.annotation.Resource but with the capability of creating specific JAX-WS service endpoints. This may either point to an explicitly defined resource by name or operate on a locally specified JAX-WS service class. Finally, this post-processor also supports the EJB 3 javax.ejb.EJB annotation, analogous to javax.annotation.Resource as well, with the capability to specify both a local bean name and a global JNDI name for fallback retrieval. The target beans can be plain POJOs as well as EJB 3 Session Beans in this case.
The common annotations supported by this post-processor are available in Java 6 (JDK 1.6) as well as in Java EE 5/6 (which provides a standalone jar for its common annotations as well, allowing for use in any Java 5 based application).
For default usage, resolving resource names as Spring bean names, simply define the following in your application context:
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
For direct JNDI access, resolving resource names as JNDI resource references within the Java EE application's "java:comp/env/" namespace, use the following:
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"> <property name="alwaysUseJndiLookup" value="true"/> </bean>
mappedName
references will always be resolved in JNDI, allowing for global JNDI names (including "java:" prefix) as well. The "alwaysUseJndiLookup" flag just affects
name
references and default names (inferred from the field name / property name).
NOTE: A default CommonAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom CommonAnnotationBeanPostProcessor bean definition!
NOTE: Annotation injection will be performed before XML injection; thus the latter configuration will override the former for properties wired through both approaches.
org.springframework.aop.target.CommonsPool2TargetSourceorg.springframework.aop.TargetSource implementation that holds objects in a configurable Apache Commons2 Pool.
By default, an instance of
GenericObjectPool
is created. Subclasses may change the type of
ObjectPool
used by overriding the
createObjectPool()
method.
Provides many configuration properties mirroring those of the Commons Pool
GenericObjectPool
class; these properties are passed to the
GenericObjectPool
during construction. If creating a subclass of this class to change the
ObjectPool
implementation type, pass in the values of configuration properties that are relevant to your chosen implementation.
The
testOnBorrow
,
testOnReturn
and
testWhileIdle
properties are explicitly not mirrored because the implementation of
PoolableObjectFactory
used by this class does not implement meaningful validation. All exposed Commons Pool properties use the corresponding Commons Pool defaults.
Compatible with Apache Commons Pool 2.4, as of Spring 4.2.
org.springframework.context.annotation.ComponentScansContainer annotation that aggregates several ComponentScan annotations.
Can be used natively, declaring several nested ComponentScan annotations. Can also be used in conjunction with Java 8's support for repeatable annotations, where ComponentScan can simply be declared several times on the same method, implicitly generating this container annotation.
org.springframework.cache.support.CompositeCacheManagerComposite CacheManager implementation that iterates over a given collection of delegate CacheManager instances.
Allows NoOpCacheManager to be automatically added to the end of the list for handling cache declarations without a backing store. Otherwise, any custom CacheManager may play that role of the last delegate as well, lazily creating cache regions for any requested name.
Note: Regular CacheManagers that this composite manager delegates to need to return
null
from
#getCache(String)
if they are unaware of the specified cache name, allowing for iteration to the next delegate in line. However, most CacheManager implementations fall back to lazy creation of named caches once requested; check out the specific configuration details for a 'static' mode with fixed cache names, if available.
A generic composite servlet Filter that just delegates its behavior to a chain (list) of user-supplied filters, achieving the functionality of a FilterChain, but conveniently using only Filter instances.
This is useful for filters that require dependency injection, and can therefore be set up in a Spring application context. Typically, this composite would be used in conjunction with DelegatingFilterProxy, so that it can be declared in Spring but applied to a servlet context.
org.springframework.util.CompositeIterator
Composite iterator that combines multiple other iterators, as registered via
#add(Iterator)
.
This implementation maintains a linked set of iterators which are invoked in sequence until all iterators are exhausted.
org.springframework.core.env.CompositePropertySource
Composite PropertySource implementation that iterates over a set of PropertySource instances. Necessary in cases where multiple property sources share the same name, e.g. when multiple values are supplied to
@PropertySource
.
As of Spring 4.1.2, this class extends EnumerablePropertySource instead of plain PropertySource, exposing
#getPropertyNames()
based on the accumulated property names from all contained sources (as far as possible).
Implements the RequestCondition contract by delegating to multiple
RequestCondition
types and using a logical conjunction (' && ') to ensure all conditions match a given request.
When
CompositeRequestCondition
instances are combined or compared they are expected to (a) contain the same number of conditions and (b) that conditions in the respective index are of the same type. It is acceptable to provide
null
conditions or no conditions at all to the constructor.
Implements the RequestCondition contract by delegating to multiple
RequestCondition
types and using a logical conjunction (' && ') to ensure all conditions match a given request.
When
CompositeRequestCondition
instances are combined or compared they are expected to (a) contain the same number of conditions and (b) that conditions in the respective index are of the same type. It is acceptable to provide
null
conditions or no conditions at all to the constructor.
Represents a template expression broken into pieces. Each piece will be an Expression but pure text parts to the template will be represented as LiteralExpression objects. An example of a template expression might be:
"Hello ${getName()}"
which will be represented as a CompositeStringExpression of two parts. The first part being a LiteralExpression representing 'Hello ' and the second part being a real expression that will call
getName()
when invoked.
org.springframework.util.comparator.CompoundComparator
A comparator that chains a sequence of one or more Comparators.
A compound comparator calls each Comparator in sequence until a single Comparator returns a non-zero result, or the comparators are exhausted and zero is returned.
This facilitates in-memory sorting similar to multi-column sorting in SQL. The order of any single Comparator in the list can also be reversed.
org.springframework.aop.interceptor.ConcurrencyThrottleInterceptorInterceptor that throttles concurrent access, blocking invocations if a specified concurrency limit is reached.
Can be applied to methods of local services that involve heavy use of system resources, in a scenario where it is more efficient to throttle concurrency for a specific service rather than restricting the entire thread pool (e.g. the web container's thread pool).
The default concurrency limit of this interceptor is 1. Specify the "concurrencyLimit" bean property to change this value.
org.springframework.core.task.support.ConcurrentExecutorAdapterAdapter that exposes the java.util.concurrent.Executor interface for any Spring org.springframework.core.task.TaskExecutor.
This is less useful as of Spring 3.0, since TaskExecutor itself extends the Executor interface. The adapter is only relevant for hiding the TaskExecutor nature of a given object now, solely exposing the standard Executor interface to a client.
org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBeanFactoryBean for easy configuration of a ConcurrentMapCache when used within a Spring container. Can be configured through bean properties; uses the assigned Spring bean name as the default cache name.
Useful for testing or simple caching scenarios, typically in combination with org.springframework.cache.support.SimpleCacheManager or dynamically through ConcurrentMapCacheManager.
org.springframework.scheduling.concurrent.ConcurrentTaskExecutor
Adapter that takes a
java.util.concurrent.Executor
and exposes a Spring org.springframework.core.task.TaskExecutor for it. Also detects an extended
java.util.concurrent.ExecutorService
, adapting the org.springframework.core.task.AsyncTaskExecutor interface accordingly.
Autodetects a JSR-236 javax.enterprise.concurrent.ManagedExecutorService in order to expose javax.enterprise.concurrent.ManagedTask adapters for it, exposing a long-running hint based on SchedulingAwareRunnable and an identity name based on the given Runnable/Callable's
toString()
. For JSR-236 style lookup in a Java EE 7 environment, consider using DefaultManagedTaskExecutor.
Note that there is a pre-built ThreadPoolTaskExecutor that allows for defining a java.util.concurrent.ThreadPoolExecutor in bean style, exposing it as a Spring org.springframework.core.task.TaskExecutor directly. This is a convenient alternative to a raw ThreadPoolExecutor definition with a separate definition of the present adapter class.
org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecoratorWrap a org.springframework.web.socket.WebSocketSession to guarantee only one thread can send messages at a time.
If a send is slow, subsequent attempts to send more messages from other threads will not be able to acquire the flush lock and messages will be buffered instead. At that time, the specified buffer-size limit and send-time limit will be checked and the session will be closed if the limits are exceeded.
org.springframework.context.annotation.ConditionalIndicates that a component is only eligible for registration when all specified conditions match.
A condition is any state that can be determined programmatically before the bean definition is due to be registered (see Condition for details).
The
@Conditional
annotation may be used in any of the following ways:
@Component
, including Configuration classes
If a
@Configuration
class is marked with
@Conditional
, all of the
@Bean
methods, Import annotations, and ComponentScan annotations associated with that class will be subject to the conditions.
NOTE
: Inheritance of
@Conditional
annotations is not supported; any conditions from superclasses or from overridden methods will not be considered. In order to enforce these semantics,
@Conditional
itself is not declared as java.lang.annotation.Inherited; furthermore, any custom
composed annotation
that is meta-annotated with
@Conditional
must not be declared as
@Inherited
.
Allows a Converter, GenericConverter or ConverterFactory to conditionally execute based on attributes of the
source
and
target
TypeDescriptor.
Often used to selectively match custom conversion logic based on the presence of a field or class-level characteristic, such as an annotation or method. For example, when converting from a String field to a Date field, an implementation might return
true
if the target field has also been annotated with
@DateTimeFormat
.
As another example, when converting from a String field to an
Account
field, an implementation might return
true
if the target Account class defines a
public static findAccount(String)
method.
Spring-configurable
FileTypeMap
implementation that will read MIME type to file extension mappings from a standard JavaMail MIME type mapping file, using a standard
MimetypesFileTypeMap
underneath.
The mapping file should be in the following format, as specified by the Java Activation Framework:
# map text/html to .htm and .html files text/html html htm HTML HTM
Lines starting with
#
are treated as comments and are ignored. All other lines are treated as mappings. Each mapping line should contain the MIME type as the first entry and then each file extension to map to that MIME type as subsequent entries. Each entry is separated by spaces or tabs.
By default, the mappings in the
mime.types
file located in the same package as this class are used, which cover many common file extensions (in contrast to the out-of-the-box mappings in
activation.jar
). This can be overridden using the
mappingLocation
property.
Additional mappings can be added via the
mappings
bean property, as lines that follow the
mime.types
file format.
BeanFactoryPostProcessor used for bootstrapping processing of Configuration classes.
Registered by default when using
<context:annotation-config/>
or
<context:component-scan/>
. Otherwise, may be declared manually as with any other BeanFactoryPostProcessor.
This post processor is
Ordered#HIGHEST_PRECEDENCE
as it is important that any Bean methods declared in Configuration classes have their respective bean definitions registered before any other BeanFactoryPostProcessor executes.
A Condition that offers more fine-grained control when used with
@Configuration
. Allows certain Conditions to adapt when they match based on the configuration phase. For example, a condition that checks if a bean has already been registered might choose to only be evaluated during the
REGISTER_BEAN
ConfigurationPhase.
Helper class for managing a JMS javax.jms.ConnectionFactory, in particular for obtaining transactional JMS resources for a given ConnectionFactory.
Mainly for internal use within the framework. Used by org.springframework.jms.core.JmsTemplate as well as org.springframework.jms.listener.DefaultMessageListenerContainer.
org.springframework.jca.cci.connection.ConnectionHolderConnection holder, wrapping a CCI Connection.
CciLocalTransactionManager binds instances of this class to the thread, for a given ConnectionFactory.
Note: This is an SPI class, not intended to be used by applications.
org.springframework.jdbc.datasource.ConnectionProxySubinterface of java.sql.Connection to be implemented by Connection proxies. Allows access to the underlying target Connection.
This interface can be checked when there is a need to cast to a native JDBC Connection such as Oracle's OracleConnection. Alternatively, all such connections also support JDBC 4.0's
Connection#unwrap
.
An adapter for a target CCI javax.resource.cci.ConnectionFactory, applying the given ConnectionSpec to every standard
getConnection()
call, that is, implicitly invoking
getConnection(ConnectionSpec)
on the target. All other methods simply delegate to the corresponding methods of the target ConnectionFactory.
Can be used to proxy a target JNDI ConnectionFactory that does not have a ConnectionSpec configured. Client code can work with the ConnectionFactory without passing in a ConnectionSpec on every
getConnection()
call.
In the following example, client code can simply transparently work with the preconfigured "myConnectionFactory", implicitly accessing "myTargetConnectionFactory" with the specified user credentials.
<bean id="myTargetConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/cci/mycf"/> </bean> <bean id="myConnectionFactory" class="org.springframework.jca.cci.connection.ConnectionSpecConnectionFactoryAdapter"> <property name="targetConnectionFactory" ref="myTargetConnectionFactory"/> <property name="connectionSpec"> <bean class="your.resource.adapter.ConnectionSpecImpl"> <property name="username" value="myusername"/> <property name="password" value="mypassword"/> </bean> </property> </bean>
If the "connectionSpec" is empty, this proxy will simply delegate to the standard
getConnection()
method of the target ConnectionFactory. This can be used to keep a UserCredentialsConnectionFactoryAdapter bean definition just for the
option
of implicitly passing in a ConnectionSpec if the particular target ConnectionFactory requires it.
FactoryBean that creates a JSR-160 JMXConnectorServer, optionally registers it with the MBeanServer and then starts it.
The
JMXConnectorServer
can be started in a separate thread by setting the
threaded
property to
true
. You can configure this thread to be a daemon thread by setting the
daemon
property to
true
.
The
JMXConnectorServer
is correctly shutdown when an instance of this class is destroyed on shutdown of the containing
ApplicationContext
.
Intercepts the construction of a new object.
The user should implement the
method to modify the original behavior. E.g. the following class implements a singleton interceptor (allows only one unique instance for the intercepted class):
class DebuggingInterceptor implements ConstructorInterceptor { Object instance=null; Object construct(ConstructorInvocation i) throws Throwable { if(instance==null) { return instance=i.proceed(); } else { throw new Exception("singleton does not allow multiple instance"); } } }
org.springframework.expression.spel.ast.ConstructorReference
Represents the invocation of a constructor. Either a constructor on a regular type or construction of an array. When an array is constructed, an initializer can be specified.
Examples: new String('hello world') new int[]{1,2,3,4} new int[3] new int[3]{1,2,3}
org.springframework.web.util.ContentCachingRequestWrapper
javax.servlet.http.HttpServletRequest wrapper that caches all content read from the
input stream
and
reader
, and allows this content to be retrieved via a
byte array
.
Used e.g. by org.springframework.web.filter.AbstractRequestLoggingFilter. Note: As of Spring Framework 5.0, this wrapper is built on the Servlet 3.1 API.
org.springframework.web.util.ContentCachingResponseWrapper
javax.servlet.http.HttpServletResponse wrapper that caches all content written to the
output stream
and
writer
, and allows this content to be retrieved via a
byte array
.
Used e.g. by org.springframework.web.filter.ShallowEtagHeaderFilter. Note: As of Spring Framework 5.0, this wrapper is built on the Servlet 3.1 API.
org.springframework.web.servlet.view.ContentNegotiatingViewResolver
Implementation of ViewResolver that resolves a view based on the request file name or
Accept
header.
The
ContentNegotiatingViewResolver
does not resolve views itself, but delegates to other ViewResolvers. By default, these other view resolvers are picked up automatically from the application context, though they can also be set explicitly by using the
viewResolvers
property.
Note
that in order for this view resolver to work properly, the
order
property needs to be set to a higher precedence than the others (the default is
Ordered#HIGHEST_PRECEDENCE
).
This view resolver uses the requested MediaType to select a suitable View for a request. The requested media type is determined through the configured ContentNegotiationManager. Once the requested media type has been determined, this resolver queries each delegate view resolver for a View and determines if the requested media type is compatible with the view's content type ). The most compatible view is returned.
Additionally, this view resolver exposes the
defaultViews
property, allowing you to override the views provided by the view resolvers. Note that these default views are offered as candidates, and still need have the content type requested (via file extension, parameter, or
Accept
header, described above).
For example, if the request path is
/view.html
, this view resolver will look for a view that has the
text/html
content type (based on the
html
file extension). A request for
/view
with a
text/html
request
Accept
header has the same result.
Central class to determine requested MediaType for a request. This is done by delegating to a list of configured
ContentNegotiationStrategy
instances.
Also provides methods to look up file extensions for a media type. This is done by delegating to the list of configured
MediaTypeFileExtensionResolver
instances.
Factory to create a
ContentNegotiationManager
and configure it with one or more ContentNegotiationStrategy instances.
As of 5.0 you can set the exact strategies to use via
#setStrategies(List)
.
As an alternative you can also rely on the set of defaults described below which can be turned on or off or customized through the methods of this builder:
Property Setter Underlying Strategy Default Setting
#setFavorPathExtension
PathExtensionContentNegotiationStrategy On
favorParameter
ParameterContentNegotiationStrategy Off
ignoreAcceptHeader
HeaderContentNegotiationStrategy On
defaultContentType
FixedContentNegotiationStrategy Not set
defaultContentTypeStrategy
ContentNegotiationStrategy Not set
Note:
if you must use URL-based content type resolution, the use of a query parameter is simpler and preferable to the use of a path extension since the latter can cause issues with URI variables, path parameters, and URI decoding. Consider setting
#setFavorPathExtension
to false or otherwise set the strategies to use explicitly via
#setStrategies(List)
.
org.springframework.test.web.servlet.result.ContentResultMatchers
Factory for response content assertions.
An instance of this class is typically accessed via
MockMvcResultMatchers#content
.
Web application listener that cleans up remaining disposable attributes in the ServletContext, i.e. attributes which implement DisposableBean and haven't been removed before. This is typically used for destroying objects in "application" scope, for which the lifecycle implies destruction at the very end of the web application's shutdown phase.
org.springframework.test.context.ContextHierarchy
@ContextHierarchy
is a class-level annotation that is used to define a hierarchy of org.springframework.context.ApplicationContext for integration tests. Examples
The following JUnit-based examples demonstrate common configuration scenarios for integration tests that require the use of context hierarchies.
Single Test Class with Context Hierarchy
ControllerIntegrationTests
represents a typical integration testing scenario for a Spring MVC web application by declaring a context hierarchy consisting of two levels, one for the
root
WebApplicationContext
(with
TestAppConfig
) and one for the
dispatcher servlet
WebApplicationContext
(with
WebConfig
). The
WebApplicationContext
that is
autowired
into the test instance is the one for the child context (i.e., the lowest context in the hierarchy).
@RunWith(SpringRunner.class) @WebAppConfiguration @ContextHierarchy({ @ContextConfiguration(classes = TestAppConfig.class), @ContextConfiguration(classes = WebConfig.class) }) public class ControllerIntegrationTests { @Autowired private WebApplicationContext wac; // ... }
Class Hierarchy with Implicit Parent Context
The following test classes define a context hierarchy within a test class hierarchy.
AbstractWebTests
declares the configuration for a root
WebApplicationContext
in a Spring-powered web application. Note, however, that
AbstractWebTests
does not declare
@ContextHierarchy
; consequently, subclasses of
AbstractWebTests
can optionally participate in a context hierarchy or follow the standard semantics for
@ContextConfiguration
.
SoapWebServiceTests
and
RestWebServiceTests
both extend
AbstractWebTests
and define a context hierarchy via
@ContextHierarchy
. The result is that three application contexts will be loaded (one for each declaration of
@ContextConfiguration
, and the application context loaded based on the configuration in
AbstractWebTests
will be set as the parent context for each of the contexts loaded for the concrete subclasses.
@RunWith(SpringRunner.class) @WebAppConfiguration @ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml") public abstract class AbstractWebTests {} @ContextHierarchy(@ContextConfiguration("/spring/soap-ws-config.xml") public class SoapWebServiceTests extends AbstractWebTests {} @ContextHierarchy(@ContextConfiguration("/spring/rest-ws-config.xml") public class RestWebServiceTests extends AbstractWebTests {}
Class Hierarchy with Merged Context Hierarchy Configuration
The following classes demonstrate the use of
named
hierarchy levels in order to
merge
the configuration for specific levels in a context hierarchy.
BaseTests
defines two levels in the hierarchy,
parent
and
child
.
ExtendedTests
extends
BaseTests
and instructs the Spring TestContext Framework to merge the context configuration for the
child
hierarchy level, simply by ensuring that the names declared via
ContextConfiguration#name
are both
"child"
. The result is that three application contexts will be loaded: one for
"/app-config.xml"
, one for
"/user-config.xml"
, and one for
{"/user-config.xml", "/order-config.xml"}
. As with the previous example, the application context loaded from
"/app-config.xml"
will be set as the parent context for the contexts loaded from
"/user-config.xml"
and
{"/user-config.xml", "/order-config.xml"}
.
@RunWith(SpringRunner.class) @ContextHierarchy({ @ContextConfiguration(name = "parent", locations = "/app-config.xml"), @ContextConfiguration(name = "child", locations = "/user-config.xml") }) public class BaseTests {} @ContextHierarchy( @ContextConfiguration(name = "child", locations = "/order-config.xml") ) public class ExtendedTests extends BaseTests {}
Class Hierarchy with Overridden Context Hierarchy Configuration
In contrast to the previous example, this example demonstrates how to
override
the configuration for a given named level in a context hierarchy by setting the
ContextConfiguration#inheritLocations
flag to
false
. Consequently, the application context for
ExtendedTests
will be loaded only from
"/test-user-config.xml"
and will have its parent set to the context loaded from
"/app-config.xml"
.
@RunWith(SpringRunner.class) @ContextHierarchy({ @ContextConfiguration(name = "parent", locations = "/app-config.xml"), @ContextConfiguration(name = "child", locations = "/user-config.xml") }) public class BaseTests {} @ContextHierarchy( @ContextConfiguration(name = "child", locations = "/test-user-config.xml", inheritLocations = false) ) public class ExtendedTests extends BaseTests {}
As of Spring Framework 4.0, this annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.web.context.ContextLoaderListenerBootstrap listener to start up and shut down Spring's root WebApplicationContext. Simply delegates to ContextLoader as well as to ContextCleanupListener.
As of Spring 3.1,
ContextLoaderListener
supports injecting the root web application context via the
#ContextLoaderListener(WebApplicationContext)
constructor, allowing for programmatic configuration in Servlet 3.0+ environments. See org.springframework.web.WebApplicationInitializer for usage examples.
HttpHandler
delegating requests to one of several
HttpHandler
's based on simple, prefix-based mappings.
This is intended as a coarse-grained mechanism for delegating requests to one of several applications -- each represented by an
HttpHandler
, with the application "context path" (the prefix-based mapping) exposed via
ServerHttpRequest#getPath()
.
Specialization of Component for classes that declare ExceptionHandler, InitBinder, or ModelAttribute methods to be shared across multiple
@Controller
classes.
Classes with
@ControllerAdvice
can be declared explicitly as Spring beans or auto-detected via classpath scanning. All such beans are sorted via org.springframework.core.annotation.AnnotationAwareOrderComparator, i.e. based on org.springframework.core.annotation.Order and org.springframework.core.Ordered, and applied in that order at runtime. For handling exceptions, an
@ExceptionHandler
will be picked on the first advice with a matching exception handler method. For model attributes and
InitBinder
initialization,
@ModelAttribute
and
@InitBinder
methods will also follow
@ControllerAdvice
order.
Note: For
@ExceptionHandler
methods, a root exception match will be preferred to just matching a cause of the current exception, among the handler methods of a particular advice bean. However, a cause match on a higher-priority advice will still be preferred to a any match (whether root or cause level) on a lower-priority advice bean. As a consequence, please declare your primary root exception mappings on a prioritized advice bean with a corresponding order!
By default the methods in an
@ControllerAdvice
apply globally to all Controllers. Use selectors
#annotations()
,
#basePackageClasses()
, and
#basePackages()
(or its alias
#value()
) to define a more narrow subset of targeted Controllers. If multiple selectors are declared, OR logic is applied, meaning selected Controllers should match at least one selector. Note that selector checks are performed at runtime and so adding many selectors may negatively impact performance and add complexity.
Encapsulates information about an ControllerAdvice Spring-managed bean without necessarily requiring it to be instantiated.
The
#findAnnotatedBeans(ApplicationContext)
method can be used to discover such beans. However, a
ControllerAdviceBean
may be created from any object, including ones without an
@ControllerAdvice
.
Interceptor that places the configured ConversionService in request scope so it's available during request processing. The request attribute name is "org.springframework.core.convert.ConversionService", the value of
ConversionService.class.getName()
.
Mainly for use within JSP tags such as the spring:eval tag.
org.springframework.context.support.ConversionServiceFactoryBean
A factory providing convenient access to a ConversionService configured with converters appropriate for most environments. Set the
"converters"
property to supplement the default converters.
This implementation creates a DefaultConversionService. Subclasses may override
#createConversionService()
in order to return a GenericConversionService instance of their choosing.
Like all
FactoryBean
implementations, this class is suitable for use when configuring a Spring application context using Spring
<beans>
XML. When configuring the container with org.springframework.context.annotation.Configuration classes, simply instantiate, configure and return the appropriate
ConversionService
object from a method.
Base class that can be used to implement a standard javax.websocket.Encoder and/or javax.websocket.Decoder. It provides encode and decode method implementations that delegate to a Spring ConversionService.
By default, this class looks up a ConversionService registered in the
active ApplicationContext
under the name
'webSocketConversionService'
. This works fine for both client and server endpoints, in a Servlet container environment. If not running in a Servlet container, subclasses will need to override the
#getConversionService()
method to provide an alternative lookup strategy.
Subclasses can extend this class and should also implement one or both of javax.websocket.Encoder and javax.websocket.Decoder. For convenience ConvertingEncoderDecoderSupport.BinaryEncoder, ConvertingEncoderDecoderSupport.BinaryDecoder, ConvertingEncoderDecoderSupport.TextEncoder and ConvertingEncoderDecoderSupport.TextDecoder subclasses are provided.
Since JSR-356 only allows Encoder/Decoder to be registered by type, instances of this class are therefore managed by the WebSocket runtime, and do not need to be registered as Spring Beans. They can, however, by injected with Spring-managed dependencies via Autowired.
Converters to convert between the
type
and
String
or
ByteBuffer
should be registered.
Helper class for cookie generation, carrying cookie descriptor settings as bean properties and being able to add and remove cookie to/from a given response.
Can serve as base class for components that generate specific cookies, such as CookieLocaleResolver and CookieThemeResolver.
org.springframework.web.servlet.i18n.CookieLocaleResolverLocaleResolver implementation that uses a cookie sent back to the user in case of a custom setting, with a fallback to the specified default locale or the request's accept-header locale.
This is particularly useful for stateless applications without user sessions. The cookie may optionally contain an associated time zone value as well; alternatively, you may specify a default time zone.
Custom controllers can override the user's locale and time zone by calling
#setLocale(Context)
on the resolver, e.g. responding to a locale change request. As a more convenient alternative, consider using
org.springframework.web.servlet.support.RequestContext#changeLocale
.
Factory for response cookie assertions.
An instance of this class is typically accessed via
MockMvcResultMatchers#cookie
.
ThemeResolver implementation that uses a cookie sent back to the user in case of a custom setting, with a fallback to the default theme. This is particularly useful for stateless applications without user sessions.
Custom controllers can thus override the user's theme by calling
setThemeName
, e.g. responding to a certain theme change request.
Resolve method arguments annotated with
@CookieValue
.
An
@CookieValue
is a named value that is resolved from a cookie. It has a required flag and a default value to fall back on when the cookie does not exist.
javax.servlet.Filter that handles CORS preflight requests and intercepts CORS simple and actual requests thanks to a CorsProcessor implementation (DefaultCorsProcessor by default) in order to add the relevant CORS response headers (like
Access-Control-Allow-Origin
) using the provided CorsConfigurationSource (for example an UrlBasedCorsConfigurationSource instance.
This is an alternative to Spring MVC Java config and XML namespace CORS configuration, useful for applications depending only on spring-web (not on spring-webmvc) or for security constraints requiring CORS checks to be performed at javax.servlet.Filter level.
This filter could be used in conjunction with DelegatingFilterProxy in order to help with its initialization.
org.springframework.web.cors.reactive.CorsWebFilter
WebFilter that handles CORS preflight requests and intercepts CORS simple and actual requests thanks to a CorsProcessor implementation (DefaultCorsProcessor by default) in order to add the relevant CORS response headers (like
Access-Control-Allow-Origin
) using the provided CorsConfigurationSource (for example an UrlBasedCorsConfigurationSource instance.
This is an alternative to Spring WebFlux Java config CORS configuration, mostly useful for applications using the functional API.
org.springframework.scheduling.support.CronSequenceGeneratorDate sequence generator for a Crontab pattern , allowing clients to specify a pattern that the sequence matches.
The pattern is a list of six single space-separated fields: representing second, minute, hour, day, month, weekday. Month and weekday names can be given as the first three letters of the English names.
Example patterns:
A Spring FactoryBean for creating a Quartz org.quartz.CronTrigger instance, supporting bean-style usage for trigger configuration.
CronTrigger(Impl)
itself is already a JavaBean but lacks sensible defaults. This class uses the Spring bean name as job name, the Quartz default group ("DEFAULT") as job group, the current time as start time, and indefinite repetition, if not specified.
This class will also register the trigger with the job name and group of a given org.quartz.JobDetail. This allows SchedulerFactoryBean to automatically register a trigger for the corresponding JobDetail, instead of registering the JobDetail separately.
org.springframework.web.bind.annotation.CrossOriginMarks the annotated method or type as permitting cross origin requests.
By default all origins and headers are permitted, credentials are not allowed, and the maximum age is set to 1800 seconds (30 minutes). The list of HTTP methods is set to the methods on the
@RequestMapping
if not explicitly set on
@CrossOrigin
.
NOTE:
@CrossOrigin
is processed if an appropriate
HandlerMapping
-
HandlerAdapter
pair is configured such as the
RequestMappingHandlerMapping
-
RequestMappingHandlerAdapter
pair which are the default in the MVC Java config and the MVC namespace.
A ResourceTransformer implementation that modifies links in a CSS file to match the public URL paths that should be exposed to clients (e.g. with an MD5 content-based hash inserted in the URL).
The implementation looks for links in CSS
@import
statements and also inside CSS
url()
functions. All links are then passed through the ResourceResolverChain and resolved relative to the location of the containing CSS file. If successfully resolved, the link is modified, otherwise the original link is preserved.
A ResourceTransformer implementation that modifies links in a CSS file to match the public URL paths that should be exposed to clients (e.g. with an MD5 content-based hash inserted in the URL).
The implementation looks for links in CSS
@import
statements and also inside CSS
url()
functions. All links are then passed through the ResourceResolverChain and resolved relative to the location of the containing CSS file. If successfully resolved, the link is modified, otherwise the original link is preserved.
A org.springframework.beans.factory.config.BeanFactoryPostProcessor implementation that allows for convenient registration of custom autowire qualifier types.
<bean id="customAutowireConfigurer" class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer"> <property name="customQualifierTypes"> <set> <value>mypackage.MyQualifier</value> </set> </property> </bean>
org.springframework.beans.propertyeditors.CustomBooleanEditor
Property editor for Boolean/boolean properties.
This is not meant to be used as system PropertyEditor but rather as locale-specific Boolean editor within custom controller code, to parse UI-caused boolean strings into boolean properties of beans and check them in the UI form.
In web MVC code, this editor will typically be registered with
binder.registerCustomEditor
calls.
Property editor for Collections, converting any source Collection to a given target Collection type.
By default registered for Set, SortedSet and List, to automatically convert any given Collection to one of those target types if the type does not match the target property.
org.springframework.beans.propertyeditors.CustomDateEditor
Property editor for
java.util.Date
, supporting a custom
java.text.DateFormat
.
This is not meant to be used as system PropertyEditor but rather as locale-specific date editor within custom controller code, parsing user-entered number strings into Date properties of beans and rendering them in the UI form.
In web MVC code, this editor will typically be registered with
binder.registerCustomEditor
.
BeanFactoryPostProcessor implementation that allows for convenient registration of custom PropertyEditor.
In case you want to register PropertyEditor instances, the recommended usage as of Spring 2.0 is to use custom PropertyEditorRegistrar implementations that in turn register any desired editor instances on a given org.springframework.beans.PropertyEditorRegistry. Each PropertyEditorRegistrar can register any number of custom editors.
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="propertyEditorRegistrars"> <list> <bean class="mypackage.MyCustomDateEditorRegistrar"/> <bean class="mypackage.MyObjectEditorRegistrar"/> </list> </property> </bean>
It's perfectly fine to register PropertyEditor
classes
via the
customEditors
property. Spring will create fresh instances of them for each editing attempt then:
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="java.util.Date" value="mypackage.MyCustomDateEditor"/> <entry key="mypackage.MyObject" value="mypackage.MyObjectEditor"/> </map> </property> </bean>
Note, that you shouldn't register PropertyEditor bean instances via the
customEditors
property as PropertyEditors are stateful and the instances will then have to be synchronized for every editing attempt. In case you need control over the instantiation process of PropertyEditors, use a PropertyEditorRegistrar to register them.
Also supports "java.lang.String[]"-style array class names and primitive class names (e.g. "boolean"). Delegates to ClassUtils for actual class name resolution.
NOTE: Custom property editors registered with this configurer do not apply to data binding. Custom editors for data binding need to be registered on the org.springframework.validation.DataBinder: Use a common base class or delegate to common PropertyEditorRegistrar implementations to reuse editor registration there.
org.springframework.beans.propertyeditors.CustomNumberEditor
Property editor for any Number subclass such as Short, Integer, Long, BigInteger, Float, Double, BigDecimal. Can use a given NumberFormat for (locale-specific) parsing and rendering, or alternatively the default
decode
/
valueOf
/
toString
methods.
This is not meant to be used as system PropertyEditor but rather as locale-specific number editor within custom controller code, parsing user-entered number strings into Number properties of beans and rendering them in the UI form.
In web MVC code, this editor will typically be registered with
binder.registerCustomEditor
calls.
Simple BeanFactoryPostProcessor implementation that registers custom Scope with the containing ConfigurableBeanFactory.
Will register all of the supplied
scopes
with the ConfigurableListableBeanFactory that is passed to the
#postProcessBeanFactory(ConfigurableListableBeanFactory)
method.
This class allows for
declarative
registration of custom scopes. Alternatively, consider implementing a custom BeanFactoryPostProcessor that calls
ConfigurableBeanFactory#registerScope
programmatically.
MethodInterceptor
implementation that allows for highly customizable method-level tracing, using placeholders.
Trace messages are written on method entry, and if the method invocation succeeds on method exit. If an invocation results in an exception, then an exception message is written. The contents of these trace messages is fully customizable and special placeholders are available to allow you to include runtime information in your log messages. The placeholders available are:
$[methodName]
- replaced with the name of the method being invoked
$[targetClassName]
- replaced with the name of the class that is the target of the invocation
$[targetClassShortName]
- replaced with the short name of the class that is the target of the invocation
$[returnValue]
- replaced with the value returned by the invocation
$[argumentTypes]
- replaced with a comma-separated list of the short class names of the method arguments
$[arguments]
- replaced with a comma-separated list of the
String
representation of the method arguments
$[exception]
- replaced with the
String
representation of any
Throwable
raised during the invocation
$[invocationTime]
- replaced with the time, in milliseconds, taken by the method invocation
There are restrictions on which placeholders can be used in which messages: see the individual message properties for details on the valid placeholders.
org.springframework.core.codec.DataBufferDecoderSimple pass-through decoder for DataBuffers.
Note
that the "decoded" buffers returned by instances of this class should be released after usage by calling
org.springframework.core.io.buffer.DataBufferUtils#release(DataBuffer)
.
org.springframework.transaction.PlatformTransactionManager implementation for a single JDBC javax.sql.DataSource. This class is capable of working in any environment with any JDBC driver, as long as the setup uses a
javax.sql.DataSource
as its
Connection
factory mechanism. Binds a JDBC Connection from the specified DataSource to the current thread, potentially allowing for one thread-bound Connection per DataSource.
Note: The DataSource that this transaction manager operates on needs to return independent Connections. The Connections may come from a pool (the typical case), but the DataSource must not return thread-scoped / request-scoped Connections or the like. This transaction manager will associate Connections with thread-bound transactions itself, according to the specified propagation behavior. It assumes that a separate, independent Connection can be obtained even during an ongoing transaction.
Application code is required to retrieve the JDBC Connection via
DataSourceUtils#getConnection(DataSource)
instead of a standard Java EE-style
DataSource#getConnection()
call. Spring classes such as org.springframework.jdbc.core.JdbcTemplate use this strategy implicitly. If not used in combination with this transaction manager, the DataSourceUtils lookup strategy behaves exactly like the native DataSource lookup; it can thus be used in a portable fashion.
Alternatively, you can allow application code to work with the standard Java EE-style lookup pattern
DataSource#getConnection()
, for example for legacy code that is not aware of Spring at all. In that case, define a TransactionAwareDataSourceProxy for your target DataSource, and pass that proxy DataSource to your DAOs, which will automatically participate in Spring-managed transactions when accessing it.
Supports custom isolation levels, and timeouts which get applied as appropriate JDBC statement timeouts. To support the latter, application code must either use org.springframework.jdbc.core.JdbcTemplate, call
DataSourceUtils#applyTransactionTimeout
for each created JDBC Statement, or go through a TransactionAwareDataSourceProxy which will create timeout-aware JDBC Connections and Statements automatically.
Consider defining a LazyConnectionDataSourceProxy for your target DataSource, pointing both this transaction manager and your DAOs to it. This will lead to optimized handling of "empty" transactions, i.e. of transactions without any JDBC statements executed. A LazyConnectionDataSourceProxy will not fetch an actual JDBC Connection from the target DataSource until a Statement gets executed, lazily applying the specified transaction settings to the target Connection.
This transaction manager supports nested transactions via the JDBC 3.0 java.sql.Savepoint mechanism. The
"nestedTransactionAllowed"
flag defaults to "true", since nested transactions will work without restrictions on JDBC drivers that support savepoints (such as the Oracle JDBC driver).
This transaction manager can be used as a replacement for the org.springframework.transaction.jta.JtaTransactionManager in the single resource case, as it does not require a container that supports JTA, typically in combination with a locally defined JDBC DataSource (e.g. an Apache Commons DBCP connection pool). Switching between this local strategy and a JTA environment is just a matter of configuration!
As of 4.3.4, this transaction manager triggers flush callbacks on registered transaction synchronizations (if synchronization is generally active), assuming resources operating on the underlying JDBC
Connection
. This allows for setup analogous to
JtaTransactionManager
, in particular with respect to lazily registered ORM resources (e.g. a Hibernate
Session
).
Bean that checks if a database has already started up. To be referenced via "depends-on" from beans that depend on database startup, like a Hibernate SessionFactory or custom data access objects that access a DataSource directly.
Useful to defer application initialization until a database has started up. Particularly appropriate for waiting on a slowly starting Oracle database.
org.springframework.format.datetime.DateFormatterRegistrar
Configures basic date formatting for use with Spring, primarily for org.springframework.format.annotation.DateTimeFormat declarations. Applies to fields of type Date, Calendar and
long
.
Designed for direct instantiation but also exposes the static
#addDateConverters(ConverterRegistry)
utility method for ad-hoc use against any
ConverterRegistry
instance.
AOP Alliance
MethodInterceptor
that can be introduced in a chain to display verbose information about intercepted invocations to the logger.
Logs full invocation details on method entry and method exit, including invocation arguments and invocation count. This is only intended for debugging purposes; use
SimpleTraceInterceptor
or
CustomizableTraceInterceptor
for pure tracing purposes.
HttpMessageReader
that wraps and delegates to a Decoder.
Also a
HttpMessageReader
that pre-resolves decoding hints from the extra information available on the server side such as the request or controller method parameter annotations.
Indicates an issue with decoding the input stream with a focus on content related issues such as a parse failure. As opposed to more general I/O errors, illegal state, or a CodecException such as a configuration issue that a Decoder may choose to raise.
For example in server web application, a
DecodingException
would translate to a response with a 400 (bad input) status while
CodecException
would translate to 500 (server error) status.
Base class for JSF NavigationHandler implementations that want to be capable of decorating an original NavigationHandler.
Supports the standard JSF style of decoration (through a constructor argument) as well as an overloaded
handleNavigation
method with explicit NavigationHandler argument (passing in the original NavigationHandler). Subclasses are forced to implement this overloaded
handleNavigation
method. Standard JSF invocations will automatically delegate to the overloaded method, with the constructor-injected NavigationHandler as argument.
Interface to be implemented by decorating proxies, in particular Spring AOP proxies but potentially also custom proxies with decorator semantics.
Note that this interface should just be implemented if the decorated class is not within the hierarchy of the proxy class to begin with. In particular, a "target-class" proxy such as a Spring AOP CGLIB proxy should not implement it since any lookup on the target class can simply be performed on the proxy class there anyway.
Defined in the core module in order to allow #org.springframework.core.annotation.AnnotationAwareOrderComparator (and potential other candidates without spring-aop dependencies) to use it for introspection purposes, in particular annotation lookups.
org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator
BeanPostProcessor
implementation that creates AOP proxies based on all candidate
Advisor
s in the current
BeanFactory
. This class is completely generic; it contains no special code to handle any particular aspects, such as pooling aspects.
It's possible to filter out advisors - for example, to use multiple post processors of this type in the same factory - by setting the
usePrefix
property to true, in which case only advisors beginning with the DefaultAdvisorAutoProxyCreator's bean name followed by a dot (like "aapc.") will be used. This default prefix can be changed from the bean name by setting the
advisorBeanNamePrefix
property. The separator (.) will also be used in this case.
Default AopProxyFactory implementation, creating either a CGLIB proxy or a JDK dynamic proxy.
Creates a CGLIB proxy if one the following is true for a given AdvisedSupport instance:
optimize
flag is set
proxyTargetClass
flag is set
In general, specify
proxyTargetClass
to enforce a CGLIB proxy, or specify one or more interfaces to use a JDK dynamic proxy.
Default implementation of the BeanDefinitionDocumentReader interface that reads bean definitions according to the "spring-beans" DTD and XSD format (Spring's default XML bean definition format).
The structure, elements, and attribute names of the required XML document are hard-coded in this class. (Of course a transform could be run if necessary to produce this format).
<beans>
does not need to be the root element of the XML document: this class will parse all bean definition elements in the XML file, regardless of the actual root element.
Concrete BeanFactory-based PointcutAdvisor that allows for any Advice to be configured as reference to an Advice bean in the BeanFactory, as well as the Pointcut to be configured through a bean property.
Specifying the name of an advice bean instead of the advice object itself (if running within a BeanFactory) increases loose coupling at initialization time, in order to not initialize the advice object until the pointcut actually matches.
org.springframework.validation.DefaultBindingErrorProcessorDefault BindingErrorProcessor implementation.
Uses the "required" error code and the field name to resolve message codes for a missing field error.
Creates a
FieldError
for each
PropertyAccessException
given, using the
PropertyAccessException
's error code ("typeMismatch", "methodInvocation") for resolving message codes.
Default implementation of the CacheAwareContextLoaderDelegate interface.
To use a static
DefaultContextCache
, invoke the
#DefaultCacheAwareContextLoaderDelegate()
constructor; otherwise, invoke the
#DefaultCacheAwareContextLoaderDelegate(ContextCache)
and provide a custom ContextCache implementation.
A default ContentTypeResolver that checks the
MessageHeaders#CONTENT_TYPE
header or falls back to a default value.
The header value is expected to be a org.springframework.util.MimeType or a
String
that can be parsed into a
MimeType
.
Default implementation of the ContextCache API.
Uses a synchronized Map configured with a maximum size and a least recently used (LRU) eviction policy to cache ApplicationContext instances.
The maximum size may be supplied as a
constructor argument
or set via a system property or Spring property named
spring.test.context.cache.maxSize
.
The default implementation of CorsProcessor, as defined by the CORS W3C recommendation .
Note that when input CorsConfiguration is
null
, this implementation does not reject simple or actual requests outright but simply avoid adding CORS headers to the response. CORS processing is also skipped if the response already contains CORS headers, or if the request is detected as a same-origin one.
The default implementation of CorsProcessor, as defined by the CORS W3C recommendation .
Note that when input CorsConfiguration is
null
, this implementation does not reject simple or actual requests outright but simply avoid adding CORS headers to the response. CORS processing is also skipped if the response already contains CORS headers, or if the request is detected as a same-origin one.
Spring's default DocumentLoader implementation.
Simply loads Document using the standard JAXP-configured XML parser. If you want to change the DocumentBuilder that is used to load documents, then one strategy is to define a corresponding Java system property when starting your JVM. For example, to use the Oracle DocumentBuilder, you might start your application like as follows:
java -Djavax.xml.parsers.DocumentBuilderFactory=oracle.xml.jaxp.JXDocumentBuilderFactory MyMainClass
org.springframework.context.event.DefaultEventListenerFactory
Default EventListenerFactory implementation that supports the regular EventListener annotation.
Used as "catch-all" implementation by default.
org.springframework.format.support.DefaultFormattingConversionServiceA specialization of FormattingConversionService configured by default with converters and formatters appropriate for most applications.
Designed for direct instantiation but also exposes the static
#addDefaultFormatters
utility method for ad hoc use against any
FormatterRegistry
instance, just as
DefaultConversionService
exposes its own
addDefaultConverters
method.
Automatically registers formatters for JSR-354 Money & Currency, JSR-310 Date-Time and/or Joda-Time, depending on the presence of the corresponding API on the classpath.
org.springframework.jms.listener.endpoint.DefaultJmsActivationSpecFactoryDefault implementation of the JmsActivationSpecFactory interface. Supports the standard JMS properties as defined by the JCA 1.5 specification, as well as Spring's extended "maxConcurrency" and "prefetchSize" settings through autodetection of well-known vendor-specific provider properties.
An ActivationSpec factory is effectively dependent on the concrete JMS provider, e.g. on ActiveMQ. This default implementation simply guesses the ActivationSpec class name from the provider's class name ("ActiveMQResourceAdapter" -> "ActiveMQActivationSpec" in the same package, or "ActivationSpecImpl" in the same package as the ResourceAdapter class), and populates the ActivationSpec properties as suggested by the JCA 1.5 specification (Appendix B). Specify the 'activationSpecClass' property explicitly if these default naming rules do not apply.
Note: ActiveMQ, JORAM and WebSphere are supported in terms of extended settings (through the detection of their bean property naming conventions). The default ActivationSpec class detection rules may apply to other JMS providers as well.
Thanks to Agim Emruli and Laurie Chan for pointing out WebSphere MQ settings and contributing corresponding tests!
org.springframework.jms.config.DefaultJmsListenerContainerFactoryA JmsListenerContainerFactory implementation to build a regular DefaultMessageListenerContainer.
This should be the default for most users and a good transition paths for those that are used to build such container definition manually.
org.springframework.orm.jpa.DefaultJpaDialectDefault implementation of the JpaDialect interface. Used as default dialect by JpaTransactionManager.
Simply begins a standard JPA transaction in
#beginTransaction
and performs standard exception translation through EntityManagerFactoryUtils.
NOTE: Spring's JPA support requires JPA 2.1 or higher, as of Spring 5.0.
org.springframework.scheduling.concurrent.DefaultManagedAwareThreadFactoryJNDI-based variant of CustomizableThreadFactory, performing a default lookup for JSR-236's "java:comp/DefaultManagedThreadFactory" in a Java EE 7 environment, falling back to the local CustomizableThreadFactory setup if not found.
This is a convenient way to use managed threads when running in a Java EE 7 environment, simply using regular local threads otherwise - without conditional setup (i.e. without profiles).
Note: This class is not strictly JSR-236 based; it can work with any regular java.util.concurrent.ThreadFactory that can be found in JNDI. Therefore, the default JNDI name "java:comp/DefaultManagedThreadFactory" can be customized through the
"jndiName"
bean property.
JNDI-based variant of ConcurrentTaskExecutor, performing a default lookup for JSR-236's "java:comp/DefaultManagedExecutorService" in a Java EE 7 environment.
Note: This class is not strictly JSR-236 based; it can work with any regular java.util.concurrent.Executor that can be found in JNDI. The actual adapting to javax.enterprise.concurrent.ManagedExecutorService happens in the base class ConcurrentTaskExecutor itself.
org.springframework.scheduling.concurrent.DefaultManagedTaskSchedulerJNDI-based variant of ConcurrentTaskScheduler, performing a default lookup for JSR-236's "java:comp/DefaultManagedScheduledExecutorService" in a Java EE 7 environment.
Note: This class is not strictly JSR-236 based; it can work with any regular java.util.concurrent.ScheduledExecutorService that can be found in JNDI. The actual adapting to javax.enterprise.concurrent.ManagedScheduledExecutorService happens in the base class ConcurrentTaskScheduler itself.
org.springframework.validation.DefaultMessageCodesResolverDefault implementation of the MessageCodesResolver interface.
Will create two message codes for an object error, in the following order (when using the
prefixed
formatter
):
Will create four message codes for a field specification, in the following order:
For example, in case of code "typeMismatch", object name "user", field "age":
This resolution algorithm thus can be leveraged for example to show specific messages for binding errors like "required" and "typeMismatch":
In case of array, List or java.util.Map properties, both codes for specific elements and for the whole collection are generated. Assuming a field "name" of an array "groups" in object "user":
By default the
errorCode
s will be placed at the beginning of constructed message strings. The
messageCodeFormatter
property can be used to specify an alternative concatenation MessageCodeFormatter.
In order to group all codes into a specific category within your resource bundles, e.g. "validation.typeMismatch.name" instead of the default "typeMismatch.name", consider specifying a
prefix
to be applied.
A concrete implementation of AbstractMockMvcBuilder that provides the WebApplicationContext supplied to it as a constructor argument.
In addition, if the ServletContext in the supplied
WebApplicationContext
does not contain an entry for the
WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
key, the root
WebApplicationContext
will be detected and stored in the
ServletContext
under the
ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
key.
Default implementation of the org.springframework.web.multipart.MultipartHttpServletRequest interface. Provides management of pre-generated parameter values.
Used by org.springframework.web.multipart.commons.CommonsMultipartResolver.
org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolverDefault implementation of the NamespaceHandlerResolver interface. Resolves namespace URIs to implementation classes based on the mappings contained in mapping file.
By default, this implementation looks for the mapping file at
META-INF/spring.handlers
, but this can be changed using the
#DefaultNamespaceHandlerResolver(ClassLoader, String)
constructor.
Convenient Pointcut-driven Advisor implementation.
This is the most commonly used Advisor implementation. It can be used with any pointcut and advice type, except for introductions. There is normally no need to subclass this class, or to implement custom Advisors.
org.springframework.web.servlet.view.DefaultRequestToViewNameTranslatorRequestToViewNameTranslator that simply transforms the URI of the incoming request into a view name.
Can be explicitly defined as the
viewNameTranslator
bean in a org.springframework.web.servlet.DispatcherServlet context. Otherwise, a plain default instance will be used.
The default transformation simply strips leading and trailing slashes as well as the file extension of the URI, and returns the result as the view name with the configured
prefix
and a
suffix
added as appropriate.
The stripping of the leading slash and file extension can be disabled using the
stripLeadingSlash
and
stripExtension
properties, respectively.
Find below some examples of request to view name translation.
http://localhost:8080/gamecast/display.html
»
display
http://localhost:8080/gamecast/displayShoppingCart.html
»
displayShoppingCart
http://localhost:8080/gamecast/admin/index.html
»
admin/index
Default implementation of the ScopedObject interface.
Simply delegates the calls to the underlying ConfigurableBeanFactory (
ConfigurableBeanFactory#getBean(String)
/
ConfigurableBeanFactory#destroyScopedBean(String)
).
An HttpRequestHandler for serving static files using the Servlet container's "default" Servlet.
This handler is intended to be used with a "/*" mapping when the org.springframework.web.servlet.DispatcherServlet is mapped to "/", thus overriding the Servlet container's default handling of static resources. The mapping to this handler should generally be ordered as the last in the chain so that it will only execute when no other more specific mappings (i.e., to controllers) can be matched.
Requests are handled by forwarding through the RequestDispatcher obtained via the name specified through the
"defaultServletName" property
. In most cases, the
defaultServletName
does not need to be set explicitly, as the handler checks at initialization time for the presence of the default Servlet of well-known containers such as Tomcat, Jetty, Resin, WebLogic and WebSphere. However, when running in a container where the default Servlet's name is not known, or where it has been customized via server configuration, the
defaultServletName
will need to be set explicitly.
Default implementation of the TestContextBootstrapper SPI.
Uses DelegatingSmartContextLoader as the default ContextLoader.
org.springframework.transaction.support.DefaultTransactionDefinitionDefault implementation of the TransactionDefinition interface, offering bean-style configuration and sensible default values (PROPAGATION_REQUIRED, ISOLATION_DEFAULT, TIMEOUT_DEFAULT, readOnly=false).
Base class for both TransactionTemplate and org.springframework.transaction.interceptor.DefaultTransactionAttribute.
org.springframework.web.util.DefaultUriBuilderFactoryDefault implementation of UriBuilderFactory providing options to pre-configure all UriBuilder instances with common properties such as a base URI, encoding mode, and default URI variables.
Uses UriComponentsBuilder for URI building.
org.springframework.web.util.DefaultUriTemplateHandlerDefault implementation of UriTemplateHandler based on the use of UriComponentsBuilder for expanding and encoding variables.
There are also several properties to customize how URI template handling is performed, including a
baseUrl
to be used as a prefix for all URI templates and a couple of encoding related options —
parsePath
and
strictEncoding
respectively.
Converts objects to String form, generally for debugging purposes, using Spring's
toString
styling conventions.
Uses the reflective visitor pattern underneath the hood to nicely encapsulate styling algorithms for each type of styled object.
org.springframework.context.annotation.DeferredImportSelector
A variation of ImportSelector that runs after all
@Configuration
beans have been processed. This type of selector can be particularly useful when the selected imports are
@Conditional
.
Implementations can also extend the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation to indicate a precedence against other DeferredImportSelectors.
org.springframework.web.servlet.mvc.method.annotation.DeferredResultMethodReturnValueHandlerHandler for return values of type DeferredResult, ListenableFuture, and CompletionStage.
org.springframework.aop.support.DelegatePerTargetObjectIntroductionInterceptorConvenient implementation of the org.springframework.aop.IntroductionInterceptor interface.
This differs from DelegatingIntroductionInterceptor in that a single instance of this class can be used to advise multiple target objects, and each target object will have its own delegate (whereas DelegatingIntroductionInterceptor shares the same delegate, and hence the same state across all targets).
The
suppressInterface
method can be used to suppress interfaces implemented by the delegate class but which should not be introduced to the owning AOP proxy.
An instance of this class is serializable if the delegates are.
Note: There are some implementation similarities between this class and DelegatingIntroductionInterceptor that suggest a possible refactoring to extract a common ancestor class in the future.
org.springframework.jms.connection.DelegatingConnectionFactory
javax.jms.ConnectionFactory implementation that delegates all calls to a given target javax.jms.ConnectionFactory, adapting specific
create(Queue/Topic)Connection
calls to the target ConnectionFactory if necessary (e.g. when running JMS 1.0.2 API based code against a generic JMS 1.1 ConnectionFactory, such as ActiveMQ's PooledConnectionFactory).
This class allows for being subclassed, with subclasses overriding only those methods (such as
#createConnection()
) that should not simply delegate to the target ConnectionFactory.
Can also be defined as-is, wrapping a specific target ConnectionFactory, using the "shouldStopConnections" flag to indicate whether Connections obtained from the target factory are supposed to be stopped before closed. The latter may be necessary for some connection pools that simply return released connections to the pool, not stopping them while they sit in the pool.
org.springframework.web.filter.DelegatingFilterProxy
Proxy for a standard Servlet Filter, delegating to a Spring-managed bean that implements the Filter interface. Supports a "targetBeanName" filter init-param in
web.xml
, specifying the name of the target bean in the Spring application context.
web.xml
will usually contain a
DelegatingFilterProxy
definition, with the specified
filter-name
corresponding to a bean name in Spring's root application context. All calls to the filter proxy will then be delegated to that bean in the Spring context, which is required to implement the standard Servlet Filter interface.
This approach is particularly useful for Filter implementation with complex setup needs, allowing to apply the full Spring bean definition machinery to Filter instances. Alternatively, consider standard Filter setup in combination with looking up service beans from the Spring root application context.
NOTE:
The lifecycle methods defined by the Servlet Filter interface will by default
not
be delegated to the target bean, relying on the Spring application context to manage the lifecycle of that bean. Specifying the "targetFilterLifecycle" filter init-param as "true" will enforce invocation of the
Filter.init
and
Filter.destroy
lifecycle methods on the target bean, letting the servlet container manage the filter lifecycle.
As of Spring 3.1,
DelegatingFilterProxy
has been updated to optionally accept constructor parameters when using Servlet 3.0's instance-based filter registration methods, usually in conjunction with Spring 3.1's org.springframework.web.WebApplicationInitializer SPI. These constructors allow for providing the delegate Filter bean directly, or providing the application context and bean name to fetch, avoiding the need to look up the application context from the ServletContext.
This class was originally inspired by Spring Security's
FilterToBeanProxy
class, written by Ben Alex.
Convenient implementation of the org.springframework.aop.IntroductionInterceptor interface.
Subclasses merely need to extend this class and implement the interfaces to be introduced themselves. In this case the delegate is the subclass instance itself. Alternatively a separate delegate may implement the interface, and be set via the delegate bean property.
Delegates or subclasses may implement any number of interfaces. All interfaces except IntroductionInterceptor are picked up from the subclass or delegate by default.
The
suppressInterface
method can be used to suppress interfaces implemented by the delegate but which should not be introduced to the owning AOP proxy.
An instance of this class is serializable if the delegate is.
org.springframework.scheduling.quartz.DelegatingJobSimple Quartz org.quartz.Job adapter that delegates to a given java.lang.Runnable instance.
Typically used in combination with property injection on the Runnable instance, receiving parameters from the Quartz JobDataMap that way instead of via the JobExecutionContext.
org.springframework.context.support.DelegatingMessageSourceEmpty MessageSource that delegates all calls to the parent MessageSource. If no parent is available, it simply won't resolve any message.
Used as placeholder by AbstractApplicationContext, if the context doesn't define its own MessageSource. Not intended for direct use in applications.
org.springframework.web.jsf.DelegatingNavigationHandlerProxyJSF NavigationHandler implementation that delegates to a NavigationHandler bean obtained from the Spring root WebApplicationContext.
Configure this handler proxy in your
faces-config.xml
file as follows:
<application> ... <navigation-handler> org.springframework.web.jsf.DelegatingNavigationHandlerProxy </navigation-handler> ... </application>
By default, the Spring ApplicationContext will be searched for the NavigationHandler under the bean name "jsfNavigationHandler". In the simplest case, this is a plain Spring bean definition like the following. However, all of Spring's bean configuration power can be applied to such a bean, in particular all flavors of dependency injection.
<bean name="jsfNavigationHandler" class="mypackage.MyNavigationHandler"> <property name="myProperty" ref="myOtherBean"/> </bean>
The target NavigationHandler bean will typically extend the standard JSF NavigationHandler class. However, note that decorating the original NavigationHandler (the JSF provider's default handler) is
not
supported in such a scenario, since we can't inject the original handler in standard JSF style (that is, as constructor argument).
For decorating the original NavigationHandler , make sure that your target bean extends Spring's DecoratingNavigationHandler class. This allows to pass in the original handler as method argument, which this proxy automatically detects. Note that a DecoratingNavigationHandler subclass will still work as standard JSF NavigationHandler as well!
This proxy may be subclassed to change the bean name used to search for the navigation handler, change the strategy used to obtain the target handler, or change the strategy used to access the ApplicationContext (normally obtained via
FacesContextUtils#getWebApplicationContext(FacesContext)
).
JSF PhaseListener implementation that delegates to one or more Spring-managed PhaseListener beans coming from the Spring root WebApplicationContext.
Configure this listener multicaster in your
faces-config.xml
file as follows:
<application> ... <phase-listener> org.springframework.web.jsf.DelegatingPhaseListenerMulticaster </phase-listener> ... </application>
The multicaster will delegate all
beforePhase
and
afterPhase
events to all target PhaseListener beans. By default, those will simply be obtained by type: All beans in the Spring root WebApplicationContext that implement the PhaseListener interface will be fetched and invoked.
Note: This multicaster's
getPhaseId()
method will always return
ANY_PHASE
.
The phase id exposed by the target listener beans will be ignored; all events will be propagated to all listeners.
This multicaster may be subclassed to change the strategy used to obtain the listener beans, or to change the strategy used to access the ApplicationContext (normally obtained via
FacesContextUtils#getWebApplicationContext(FacesContext)
).
Delegating implementation of javax.servlet.ServletInputStream.
Used by MockHttpServletRequest; typically not directly used for testing application controllers.
org.springframework.mock.web.DelegatingServletOutputStreamDelegating implementation of javax.servlet.ServletOutputStream.
Used by MockHttpServletResponse; typically not directly used for testing application controllers.
org.springframework.ui.context.support.DelegatingThemeSourceEmpty ThemeSource that delegates all calls to the parent ThemeSource. If no parent is available, it simply won't resolve any theme.
Used as placeholder by UiApplicationContextUtils, if a context doesn't define its own ThemeSource. Not intended for direct use in applications.
org.springframework.test.web.servlet.htmlunit.DelegatingWebConnection
Implementation of WebConnection that allows delegating to various
WebConnection
implementations.
For example, if you host your JavaScript on the domain
code.jquery.com
, you might want to use the following.
WebClient webClient = new WebClient(); MockMvc mockMvc = ... MockMvcWebConnection mockConnection = new MockMvcWebConnection(mockMvc, webClient); WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*"); WebConnection httpConnection = new HttpWebConnection(webClient); WebConnection webConnection = new DelegatingWebConnection(mockConnection, new DelegateWebConnection(cdnMatcher, httpConnection)); webClient.setWebConnection(webConnection); WebClient webClient = new WebClient(); webClient.setWebConnection(webConnection);
org.springframework.web.socket.config.annotation.DelegatingWebSocketMessageBrokerConfiguration
A WebSocketMessageBrokerConfigurationSupport extension that detects beans of type WebSocketMessageBrokerConfigurer and delegates to all of them allowing callback style customization of the configuration provided in WebSocketMessageBrokerConfigurationSupport.
This class is typically imported via EnableWebSocketMessageBroker.
org.springframework.web.bind.annotation.DeleteMapping
Annotation for mapping HTTP
DELETE
requests onto specific handler methods.
Specifically,
@DeleteMapping
is a
composed annotation
that acts as a shortcut for
@RequestMapping(method = RequestMethod.DELETE)
.
Beans on which the current bean depends. Any beans specified are guaranteed to be created by the container before this bean. Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean's initialization.
May be used on any class directly or indirectly annotated with org.springframework.stereotype.Component or on methods annotated with Bean.
Using DependsOn at the class level has no effect unless component-scanning is being used. If a DependsOn-annotated class is declared via XML, DependsOn annotation metadata is ignored, and
<bean depends-on="..."/>
is respected instead.
DataFieldMaxValueIncrementer that increments the maximum value of a given Derby table with the equivalent of an auto-increment column. Note: If you use this class, your Derby key column should NOT be defined as an IDENTITY column, as the sequence table does the job.
The sequence is kept in a table. There should be one sequence table per table that needs an auto-generated key.
Derby requires an additional column to be used for the insert since it is impossible to insert a null into the identity column and have the value generated. This is solved by providing the name of a dummy column that also must be created in the sequence table.
Example:
create table tab (id int not null primary key, text varchar(100)); create table tab_sequence (value int generated always as identity, dummy char(1)); insert into tab_sequence (dummy) values(null);
If "cacheSize" is set, the intermediate values are served without querying the database. If the server or your application is stopped or crashes or a transaction is rolled back, the unused values will never be served. The maximum hole size in numbering is consequently the value of cacheSize.
HINT:
Since Derby supports the JDBC 3.0
getGeneratedKeys
method, it is recommended to use IDENTITY columns directly in the tables and then utilizing a org.springframework.jdbc.support.KeyHolder when calling the with the
update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder)
method of the org.springframework.jdbc.core.JdbcTemplate.
Thanks to Endre Stolsvik for the suggestion!
org.springframework.messaging.handler.annotation.DestinationVariableAnnotation that indicates a method parameter should be bound to a template variable in a destination template string. Supported on message handling methods such as MessageMapping.
A
@DestinationVariable
template variable is always required.
Resolves method parameters annotated with org.springframework.messaging.handler.annotation.DestinationVariable.
org.springframework.beans.factory.config.DestructionAwareBeanPostProcessorSubinterface of BeanPostProcessor that adds a before-destruction callback.
The typical usage will be to invoke custom destruction callbacks on specific bean types, matching corresponding initialization callbacks.
org.springframework.beans.DirectFieldAccessorConfigurablePropertyAccessor implementation that directly accesses instance fields. Allows for direct binding to fields instead of going through JavaBean setters.
As of Spring 4.2, the vast majority of the BeanWrapper features have been merged to AbstractPropertyAccessor, which means that property traversal as well as collections and map access is now supported here as well.
A DirectFieldAccessor's default for the "extractOldValueForEditor" setting is "true", since a field can always be read without side effects.
org.springframework.validation.DirectFieldBindingResultSpecial implementation of the Errors and BindingResult interfaces, supporting registration and evaluation of binding errors on value objects. Performs direct field access instead of going through JavaBean getters.
Since Spring 4.1 this implementation is able to traverse nested fields.
org.springframework.test.annotation.DirtiesContextTest annotation which indicates that the org.springframework.context.ApplicationContext associated with a test is dirty and should therefore be closed and removed from the context cache.
Use this annotation if a test has modified the context — for example, by modifying the state of a singleton bean, modifying the state of an embedded database, etc. Subsequent tests that request the same context will be supplied a new context.
@DirtiesContext
may be used as a class-level and method-level annotation within the same class or class hierarchy. In such scenarios, the
ApplicationContext
will be marked as
dirty
before or after any such annotated method as well as before or after the current test class, depending on the configured
#methodMode
and
#classMode
.
As of Spring Framework 4.0, this annotation may be used as a meta-annotation to create custom composed annotations .
Supported Test Phases
BEFORE_CLASS
BEFORE_EACH_TEST_METHOD
BEFORE_METHOD
AFTER_METHOD
AFTER_EACH_TEST_METHOD
AFTER_CLASS
BEFORE_*
modes are supported by the org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener;
AFTER_*
modes are supported by the org.springframework.test.context.support.DirtiesContextTestExecutionListener.
@DisabledIf
is used to signal that the annotated test class or test method is
disabled
and should not be executed if the supplied
#expression
evaluates to
true
.
When applied at the class level, all test methods within that class are automatically disabled as well.
For basic examples, see the Javadoc for
#expression
.
This annotation may be used as a
meta-annotation
to create custom
composed annotations
. For example, a custom
@DisabledOnMac
annotation can be created as follows.
@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @DisabledIf( expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}", reason = "Disabled on Mac OS" ) public @interface DisabledOnMac {}
org.springframework.jdbc.datasource.DriverManagerDataSource
Simple implementation of the standard JDBC javax.sql.DataSource interface, configuring the plain old JDBC java.sql.DriverManager via bean properties, and returning a new java.sql.Connection from every
getConnection
call.
NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call.
Useful for test or standalone environments outside of a Java EE container, either as a DataSource bean in a corresponding ApplicationContext or in conjunction with a simple JNDI environment. Pool-assuming
Connection.close()
calls will simply close the Connection, so any DataSource-aware persistence code should work.
NOTE: Within special class loading environments such as OSGi, this class is effectively superseded by SimpleDriverDataSource due to general class loading issues with the JDBC DriverManager that be resolved through direct Driver usage (which is exactly what SimpleDriverDataSource does).
In a Java EE container, it is recommended to use a JNDI DataSource provided by the container. Such a DataSource can be exposed as a DataSource bean in a Spring ApplicationContext via org.springframework.jndi.JndiObjectFactoryBean, for seamless switching to and from a local DataSource bean like this class. For tests, you can then either set up a mock JNDI environment through Spring's org.springframework.mock.jndi.SimpleNamingContextBuilder, or switch the bean definition to a local DataSource (which is simpler and thus recommended).
If you need a "real" connection pool outside of a Java EE container, consider Apache Commons DBCP or C3P0 . Commons DBCP's BasicDataSource and C3P0's ComboPooledDataSource are full connection pool beans, supporting the same basic properties as this class plus specific settings (such as minimal/maximal pool size etc).
org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapterorg.springframework.orm.jpa.JpaVendorAdapter implementation for Eclipse Persistence Services (EclipseLink). Developed and tested against EclipseLink 2.4.
Exposes EclipseLink's persistence provider and EntityManager extension interface, and adapts AbstractJpaVendorAdapter's common configuration settings. No support for the detection of annotated packages (through
org.springframework.orm.jpa.persistenceunit.SmartPersistenceUnitInfo#getManagedPackages()
) since EclipseLink doesn't use package-level metadata.
FactoryBean that creates a named EhCache net.sf.ehcache.Cache instance (or a decorator that implements the net.sf.ehcache.Ehcache interface), representing a cache region within an EhCache net.sf.ehcache.CacheManager.
If the specified named cache is not configured in the cache configuration descriptor, this FactoryBean will construct an instance of a Cache with the provided name and the specified cache properties and add it to the CacheManager for later retrieval. If some or all properties are not set at configuration time, this FactoryBean will use defaults.
Note: If the named Cache instance is found, the properties will be ignored and the Cache instance will be retrieved from the CacheManager.
Note: As of Spring 5.0, Spring's EhCache support requires EhCache 2.10 or higher.
org.springframework.cache.ehcache.EhCacheManagerFactoryBeanFactoryBean that exposes an EhCache net.sf.ehcache.CacheManager instance (independent or shared), configured from a specified config location.
If no config location is specified, a CacheManager will be configured from "ehcache.xml" in the root of the class path (that is, default EhCache initialization - as defined in the EhCache docs - will apply).
Setting up a separate EhCacheManagerFactoryBean is also advisable when using EhCacheFactoryBean, as it provides a (by default) independent CacheManager instance and cares for proper shutdown of the CacheManager. EhCacheManagerFactoryBean is also necessary for loading EhCache configuration from a non-default config location.
Note: As of Spring 5.0, Spring's EhCache support requires EhCache 2.10 or higher.
org.springframework.cache.ehcache.EhCacheManagerUtils
Convenient builder methods for EhCache 2.5+ CacheManager setup, providing easy programmatic bootstrapping from a Spring-provided resource. This is primarily intended for use within
@Bean
methods in a Spring configuration class.
These methods are a simple alternative to custom CacheManager setup code. For any advanced purposes, consider using
#parseConfiguration
, customizing the configuration object, and then calling the
CacheManager#CacheManager(Configuration)
constructor.
Base class for EIS operation objects that work with the CCI API. Encapsulates a CCI ConnectionFactory and a CCI InteractionSpec.
Works with a CciTemplate instance underneath. EIS operation objects are an alternative to working with a CciTemplate directly.
org.springframework.jdbc.datasource.embedded.EmbeddedDatabase
EmbeddedDatabase
serves as a handle to an embedded database instance.
An
EmbeddedDatabase
is also a DataSource and adds a
#shutdown
operation so that the embedded database instance can be shut down gracefully.
A builder that provides a convenient API for constructing an embedded database. Usage Example
EmbeddedDatabase db = new EmbeddedDatabaseBuilder() .generateUniqueName(true) .setType(H2) .setScriptEncoding("UTF-8") .ignoreFailedDrops(true) .addScript("schema.sql") .addScripts("user_data.sql", "country_data.sql") .build(); // perform actions against the db (EmbeddedDatabase extends javax.sql.DataSource) db.shutdown();
org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory
Factory for creating an EmbeddedDatabase instance.
Callers are guaranteed that the returned database has been fully initialized and populated.
The factory can be configured as follows:
#generateUniqueDatabaseName
to set a unique, random name for the database.
#setDatabaseName
to set an explicit name for the database.
#setDatabaseType
to set the database type if you wish to use one of the supported types.
#setDatabaseConfigurer
to configure support for a custom embedded database type.
#setDatabasePopulator
to change the algorithm used to populate the database.
#setDataSourceFactory
to change the type of DataSource used to connect to the database.
After configuring the factory, call
#getDatabase()
to obtain a reference to the EmbeddedDatabase instance.
A subclass of EmbeddedDatabaseFactory that implements FactoryBean for registration as a Spring bean. Returns the actual DataSource that provides connectivity to the embedded database to Spring.
The target DataSource is returned instead of an EmbeddedDatabase proxy since the FactoryBean will manage the initialization and destruction lifecycle of the embedded database instance.
Implements DisposableBean to shutdown the embedded database when the managing Spring container is being closed.
org.springframework.beans.factory.config.EmbeddedValueResolverStringValueResolver adapter for resolving placeholders and expressions against a ConfigurableBeanFactory.
Note that this adapter resolves expressions as well, in contrast to the
ConfigurableBeanFactory#resolveEmbeddedValue
method. The BeanExpressionContext used is for the plain bean factory, with no scope specified for any contextual objects to access.
Interface to be implemented by any object that wishes to be notified of a StringValueResolver for the resolution of embedded definition values.
This is an alternative to a full ConfigurableBeanFactory dependency via the ApplicationContextAware/BeanFactoryAware interfaces.
org.springframework.context.annotation.EnableAspectJAutoProxy
Enables support for handling components marked with AspectJ's
@Aspect
annotation, similar to functionality found in Spring's
<aop:aspectj-autoproxy>
XML element. To be used on @Configuration classes as follows:
@Configuration @EnableAspectJAutoProxy public class AppConfig { @Bean public FooService fooService() { return new FooService(); } @Bean public MyAspect myAspect() { return new MyAspect(); } }
Where
FooService
is a typical POJO component and
MyAspect
is an
@Aspect
-style aspect:
public class FooService { // various methods }
@Aspect public class MyAspect { @Before("execution(* FooService+.*(..))") public void advice() { // advise FooService methods as appropriate } }
In the scenario above,
@EnableAspectJAutoProxy
ensures that
MyAspect
will be properly processed and that
FooService
will be proxied mixing in the advice that it contributes.
Users can control the type of proxy that gets created for
FooService
using the
#proxyTargetClass()
attribute. The following enables CGLIB-style 'subclass' proxies as opposed to the default interface-based JDK proxy approach.
@Configuration @EnableAspectJAutoProxy(proxyTargetClass=true) public class AppConfig { // ... }
Note that
@Aspect
beans may be component-scanned like any other. Simply mark the aspect with both
@Aspect
and
@Component
:
package com.foo; @Component public class FooService { ... } @Aspect @Component public class MyAspect { ... }
Then use the @ComponentScan annotation to pick both up:
@Configuration @ComponentScan("com.foo") @EnableAspectJAutoProxy public class AppConfig { // no explicit @Bean definitions required }
org.springframework.scheduling.annotation.EnableAsync
Enables Spring's asynchronous method execution capability, similar to functionality found in Spring's
<task:*>
XML namespace.
To be used together with @Configuration classes as follows, enabling annotation-driven async processing for an entire Spring application context:
@Configuration @EnableAsync public class AppConfig { }
MyAsyncBean
is a user-defined type with one or more methods annotated with either Spring's
@Async
annotation, the EJB 3.1
@javax.ejb.Asynchronous
annotation, or any custom annotation specified via the
#annotation
attribute. The aspect is added transparently for any registered bean, for instance via this configuration:
@Configuration public class AnotherAppConfig { @Bean public MyAsyncBean asyncBean() { return new MyAsyncBean(); } }
By default, Spring will be searching for an associated thread pool definition: either a unique org.springframework.core.task.TaskExecutor bean in the context, or an java.util.concurrent.Executor bean named "taskExecutor" otherwise. If neither of the two is resolvable, a org.springframework.core.task.SimpleAsyncTaskExecutor will be used to process async method invocations. Besides, annotated methods having a
void
return type cannot transmit any exception back to the caller. By default, such uncaught exceptions are only logged.
To customize all this, implement AsyncConfigurer and provide:
getAsyncExecutor()
method, and
getAsyncUncaughtExceptionHandler()
method.
@Configuration @EnableAsync public class AppConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(7); executor.setMaxPoolSize(42); executor.setQueueCapacity(11); executor.setThreadNamePrefix("MyExecutor-"); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return MyAsyncUncaughtExceptionHandler(); } }
If only one item needs to be customized,
null
can be returned to keep the default settings. Consider also extending from AsyncConfigurerSupport when possible.
Note: In the above example the
ThreadPoolTaskExecutor
is not a fully managed Spring bean. Add the
@Bean
annotation to the
getAsyncExecutor()
method if you want a fully managed bean. In such circumstances it is no longer necessary to manually call the
executor.initialize()
method as this will be invoked automatically when the bean is initialized.
For reference, the example above can be compared to the following Spring XML configuration:
<beans> <task:annotation-driven executor="myExecutor" exception-handler="exceptionHandler"/> <task:executor id="myExecutor" pool-size="7-42" queue-capacity="11"/> <bean id="asyncBean" class="com.foo.MyAsyncBean"/> <bean id="exceptionHandler" class="com.foo.MyAsyncUncaughtExceptionHandler"/> </beans>
The above XML-based and JavaConfig-based examples are equivalent except for the setting of the
thread name prefix
of the
Executor
; this is because the
<task:executor>
element does not expose such an attribute. This demonstrates how the JavaConfig-based approach allows for maximum configurability through direct access to actual componentry.
The
#mode
attribute controls how advice is applied: If the mode is
AdviceMode#PROXY
(the default), then the other attributes control the behavior of the proxying. Please note that proxy mode allows for interception of calls through the proxy only; local calls within the same class cannot get intercepted that way.
Note that if the
#mode
is set to
AdviceMode#ASPECTJ
, then the value of the
#proxyTargetClass
attribute will be ignored. Note also that in this case the
spring-aspects
module JAR must be present on the classpath, with compile-time weaving or load-time weaving applying the aspect to the affected classes. There is no proxy involved in such a scenario; local calls will be intercepted as well.
Enable JMS listener annotated endpoints that are created under the cover by a org.springframework.jms.config.JmsListenerContainerFactory. To be used on org.springframework.context.annotation.Configuration classes as follows:
@Configuration @EnableJms public class AppConfig { @Bean public DefaultJmsListenerContainerFactory myJmsListenerContainerFactory() { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setConnectionFactory(connectionFactory()); factory.setDestinationResolver(destinationResolver()); factory.setConcurrency("5"); return factory; } // other @Bean definitions }
The
JmsListenerContainerFactory
is responsible to create the listener container responsible for a particular endpoint. Typical implementations, as the org.springframework.jms.config.DefaultJmsListenerContainerFactory used in the sample above, provides the necessary configuration options that are supported by the underlying org.springframework.jms.listener.MessageListenerContainer.
@EnableJms
enables detection of JmsListener annotations on any Spring-managed bean in the container. For example, given a class
MyService
:
package com.acme.foo; public class MyService { @JmsListener(containerFactory = "myJmsListenerContainerFactory", destination="myQueue") public void process(String msg) { // process incoming message } }
The container factory to use is identified by the
containerFactory
attribute defining the name of the
JmsListenerContainerFactory
bean to use. When none is set a
JmsListenerContainerFactory
bean with name
jmsListenerContainerFactory
is assumed to be present.
the following configuration would ensure that every time a javax.jms.Message is received on the javax.jms.Destination named "myQueue",
MyService.process()
is called with the content of the message:
@Configuration @EnableJms public class AppConfig { @Bean public MyService myService() { return new MyService(); } // JMS infrastructure setup }
Alternatively, if
MyService
were annotated with
@Component
, the following configuration would ensure that its
@JmsListener
annotated method is invoked with a matching incoming message:
@Configuration @EnableJms @ComponentScan(basePackages="com.acme.foo") public class AppConfig { }
Note that the created containers are not registered against the application context but can be easily located for management purposes using the org.springframework.jms.config.JmsListenerEndpointRegistry.
Annotated methods can use flexible signature; in particular, it is possible to use the org.springframework.messaging.Message abstraction and related annotations, see JmsListener Javadoc for more details. For instance, the following would inject the content of the message and a custom "myCounter" JMS header:
@JmsListener(containerFactory = "myJmsListenerContainerFactory", destination="myQueue") public void process(String msg, @Header("myCounter") int counter) { // process incoming message }
These features are abstracted by the org.springframework.messaging.handler.annotation.support.MessageHandlerMethodFactory that is responsible to build the necessary invoker to process the annotated method. By default, org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory is used.
When more control is desired, a
@Configuration
class may implement JmsListenerConfigurer. This allows access to the underlying org.springframework.jms.config.JmsListenerEndpointRegistrar instance. The following example demonstrates how to specify an explicit default
JmsListenerContainerFactory
@Configuration @EnableJms public class AppConfig implements JmsListenerConfigurer { @Override public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) { registrar.setContainerFactory(myJmsListenerContainerFactory()); } @Bean public JmsListenerContainerFactory myJmsListenerContainerFactory() { // factory settings } @Bean public MyService myService() { return new MyService(); } }
For reference, the example above can be compared to the following Spring XML configuration:
<beans> <jms:annotation-driven container-factory="myJmsListenerContainerFactory"/> <bean id="myJmsListenerContainerFactory" class="org.springframework.jms.config.DefaultJmsListenerContainerFactory"> // factory settings </bean> <bean id="myService" class="com.acme.foo.MyService"/> </beans>
It is also possible to specify a custom org.springframework.jms.config.JmsListenerEndpointRegistry in case you need more control on the way the containers are created and managed. The example below also demonstrates how to customize the
JmsHandlerMethodFactory
to use with a custom org.springframework.validation.Validator so that payloads annotated with org.springframework.validation.annotation.Validated are first validated against a custom
Validator
.
@Configuration @EnableJms public class AppConfig implements JmsListenerConfigurer { @Override public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) { registrar.setEndpointRegistry(myJmsListenerEndpointRegistry()); registrar.setMessageHandlerMethodFactory(myJmsHandlerMethodFactory); } @Bean public JmsListenerEndpointRegistry myJmsListenerEndpointRegistry() { // registry configuration } @Bean public JmsHandlerMethodFactory myJmsHandlerMethodFactory() { DefaultJmsHandlerMethodFactory factory = new DefaultJmsHandlerMethodFactory(); factory.setValidator(new MyValidator()); return factory; } @Bean public MyService myService() { return new MyService(); } }
For reference, the example above can be compared to the following Spring XML configuration:
<beans> <jms:annotation-driven registry="myJmsListenerEndpointRegistry" handler-method-factory="myJmsHandlerMethodFactory"/> <bean id="myJmsListenerEndpointRegistry" class="org.springframework.jms.config.JmsListenerEndpointRegistry"> // registry configuration </bean> <bean id="myJmsHandlerMethodFactory" class="org.springframework.messaging.handler.support.DefaultJmsHandlerMethodFactory"> <property name="validator" ref="myValidator"/> </bean> <bean id="myService" class="com.acme.foo.MyService"/> </beans>
Implementing
JmsListenerConfigurer
also allows for fine-grained control over endpoints registration via the
JmsListenerEndpointRegistrar
. For example, the following configures an extra endpoint:
@Configuration @EnableJms public class AppConfig implements JmsListenerConfigurer { @Override public void configureJmsListeners(JmsListenerEndpointRegistrar registrar) { SimpleJmsListenerEndpoint myEndpoint = new SimpleJmsListenerEndpoint(); // ... configure the endpoint registrar.registerEndpoint(endpoint, anotherJmsListenerContainerFactory()); } @Bean public MyService myService() { return new MyService(); } @Bean public JmsListenerContainerFactory anotherJmsListenerContainerFactory() { // ... } // JMS infrastructure setup }
Note that all beans implementing
JmsListenerConfigurer
will be detected and invoked in a similar fashion. The example above can be translated in a regular bean definition registered in the context in case you use the XML configuration.
org.springframework.context.annotation.EnableLoadTimeWeaving
Activates a Spring LoadTimeWeaver for this application context, available as a bean with the name "loadTimeWeaver", similar to the
<context:load-time-weaver>
element in Spring XML.
To be used on @org.springframework.context.annotation.Configuration classes; the simplest possible example of which follows:
@Configuration @EnableLoadTimeWeaving public class AppConfig { // application-specific @Bean definitions ... }
The example above is equivalent to the following Spring XML configuration:
<beans> <context:load-time-weaver/> <!-- application-specific <bean> definitions --> </beans>
The
LoadTimeWeaverAware
interface Any bean that implements the interface will then receive the
LoadTimeWeaver
reference automatically; for example, Spring's JPA bootstrap support. Customizing the
LoadTimeWeaver
The default weaver is determined automatically: see DefaultContextLoadTimeWeaver.
To customize the weaver used, the
@Configuration
class annotated with
@EnableLoadTimeWeaving
may also implement the LoadTimeWeavingConfigurer interface and return a custom
LoadTimeWeaver
instance through the
#getLoadTimeWeaver
method:
@Configuration @EnableLoadTimeWeaving public class AppConfig implements LoadTimeWeavingConfigurer { @Override public LoadTimeWeaver getLoadTimeWeaver() { MyLoadTimeWeaver ltw = new MyLoadTimeWeaver(); ltw.addClassTransformer(myClassFileTransformer); // ... return ltw; } }
The example above can be compared to the following Spring XML configuration:
<beans> <context:load-time-weaver weaverClass="com.acme.MyLoadTimeWeaver"/> </beans>
The code example differs from the XML example in that it actually instantiates the
MyLoadTimeWeaver
type, meaning that it can also configure the instance, e.g. calling the
#addClassTransformer
method. This demonstrates how the code-based configuration approach is more flexible through direct programmatic access.
#aspectjWeaving()
attribute, which will cause the to be registered through
LoadTimeWeaver#addTransformer
. AspectJ weaving will be activated by default if a "META-INF/aop.xml" resource is present on the classpath. Example:
@Configuration @EnableLoadTimeWeaving(aspectjWeaving=ENABLED) public class AppConfig { }
The example above can be compared to the following Spring XML configuration:
<beans> <context:load-time-weaver aspectj-weaving="on"/> </beans>
The two examples are equivalent with one significant exception: in the XML case, the functionality of
<context:spring-configured>
is implicitly enabled when
aspectj-weaving
is "on". This does not occur when using
@EnableLoadTimeWeaving(aspectjWeaving=ENABLED)
. Instead you must explicitly add
@EnableSpringConfigured
(included in the
spring-aspects
module)
Enables default exporting of all standard
MBean
s from the Spring context, as well as well all
@ManagedResource
annotated beans.
The resulting org.springframework.jmx.export.MBeanExporter bean is defined under the name "mbeanExporter". Alternatively, consider defining a custom AnnotationMBeanExporter bean explicitly.
This annotation is modeled after and functionally equivalent to Spring XML's
<context:mbean-export/>
element.
Enables Spring's scheduled task execution capability, similar to functionality found in Spring's
<task:*>
XML namespace. To be used on @Configuration classes as follows:
@Configuration @EnableScheduling public class AppConfig { // various @Bean definitions }
This enables detection of @Scheduled annotations on any Spring-managed bean in the container. For example, given a class
MyTask
package com.myco.tasks; public class MyTask { @Scheduled(fixedRate=1000) public void work() { // task execution logic } }
the following configuration would ensure that
MyTask.work()
is called once every 1000 ms:
@Configuration @EnableScheduling public class AppConfig { @Bean public MyTask task() { return new MyTask(); } }
Alternatively, if
MyTask
were annotated with
@Component
, the following configuration would ensure that its
@Scheduled
method is invoked at the desired interval:
@Configuration @EnableScheduling @ComponentScan(basePackages="com.myco.tasks") public class AppConfig { }
Methods annotated with
@Scheduled
may even be declared directly within
@Configuration
classes:
@Configuration @EnableScheduling public class AppConfig { @Scheduled(fixedRate=1000) public void work() { // task execution logic } }
By default, will be searching for an associated scheduler definition: either a unique org.springframework.scheduling.TaskScheduler bean in the context, or a
TaskScheduler
bean named "taskScheduler" otherwise; the same lookup will also be performed for a java.util.concurrent.ScheduledExecutorService bean. If neither of the two is resolvable, a local single-threaded default scheduler will be created and used within the registrar.
When more control is desired, a
@Configuration
class may implement SchedulingConfigurer. This allows access to the underlying ScheduledTaskRegistrar instance. For example, the following example demonstrates how to customize the Executor used to execute scheduled tasks:
@Configuration @EnableScheduling public class AppConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskExecutor()); } @Bean(destroyMethod="shutdown") public Executor taskExecutor() { return Executors.newScheduledThreadPool(100); } }
Note in the example above the use of
@Bean(destroyMethod="shutdown")
. This ensures that the task executor is properly shut down when the Spring application context itself is closed.
Implementing
SchedulingConfigurer
also allows for fine-grained control over task registration via the
ScheduledTaskRegistrar
. For example, the following configures the execution of a particular bean method per a custom
Trigger
implementation:
@Configuration @EnableScheduling public class AppConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskScheduler()); taskRegistrar.addTriggerTask( new Runnable() { public void run() { myTask().work(); } }, new CustomTrigger() ); } @Bean(destroyMethod="shutdown") public Executor taskScheduler() { return Executors.newScheduledThreadPool(42); } @Bean public MyTask myTask() { return new MyTask(); } }
For reference, the example above can be compared to the following Spring XML configuration:
<beans> <task:annotation-driven scheduler="taskScheduler"/> <task:scheduler id="taskScheduler" pool-size="42"/> <task:scheduled-tasks scheduler="taskScheduler"> <task:scheduled ref="myTask" method="work" fixed-rate="1000"/> </task:scheduled-tasks> <bean id="myTask" class="com.foo.MyTask"/> </beans>
The examples are equivalent save that in XML a
fixed-rate
period is used instead of a custom
Trigger
implementation; this is because the
task:
namespace
scheduled
cannot easily expose such support. This is but one demonstration how the code-based approach allows for maximum configurability through direct access to actual componentry.
org.springframework.context.annotation.aspectj.EnableSpringConfigured
Signals the current application context to apply dependency injection to non-managed classes that are instantiated outside of the Spring bean factory (typically classes annotated with the org.springframework.beans.factory.annotation.Configurable annotation).
Similar to functionality found in Spring's
<context:spring-configured>
XML element. Often used in conjunction with org.springframework.context.annotation.EnableLoadTimeWeaving.
Enables Spring's annotation-driven transaction management capability, similar to the support found in Spring's
<tx:*>
XML namespace. To be used on org.springframework.context.annotation.Configuration classes as follows:
@Configuration @EnableTransactionManagement public class AppConfig { @Bean public FooRepository fooRepository() { // configure and return a class having @Transactional methods return new JdbcFooRepository(dataSource()); } @Bean public DataSource dataSource() { // configure and return the necessary JDBC DataSource } @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManager(dataSource()); } }
For reference, the example above can be compared to the following Spring XML configuration:
<beans> <tx:annotation-driven/> <bean id="fooRepository" class="com.foo.JdbcFooRepository"> <constructor-arg ref="dataSource"/> </bean> <bean id="dataSource" class="com.vendor.VendorDataSource"/> <bean id="transactionManager" class="org.sfwk...DataSourceTransactionManager"> <constructor-arg ref="dataSource"/> </bean> </beans>
In both of the scenarios above,
@EnableTransactionManagement
and
<tx:annotation-driven/>
are responsible for registering the necessary Spring components that power annotation-driven transaction management, such as the TransactionInterceptor and the proxy- or AspectJ-based advice that weave the interceptor into the call stack when
JdbcFooRepository
's
@Transactional
methods are invoked.
A minor difference between the two examples lies in the naming of the
PlatformTransactionManager
bean: In the
@Bean
case, the name is
"txManager"
(per the name of the method); in the XML case, the name is
"transactionManager"
. The
<tx:annotation-driven/>
is hard-wired to look for a bean named "transactionManager" by default, however
@EnableTransactionManagement
is more flexible; it will fall back to a by-type lookup for any
PlatformTransactionManager
bean in the container. Thus the name can be "txManager", "transactionManager", or "tm": it simply does not matter.
For those that wish to establish a more direct relationship between
@EnableTransactionManagement
and the exact transaction manager bean to be used, the TransactionManagementConfigurer callback interface may be implemented - notice the
implements
clause and the
@Override
-annotated method below:
@Configuration @EnableTransactionManagement public class AppConfig implements TransactionManagementConfigurer { @Bean public FooRepository fooRepository() { // configure and return a class having @Transactional methods return new JdbcFooRepository(dataSource()); } @Bean public DataSource dataSource() { // configure and return the necessary JDBC DataSource } @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManager(dataSource()); } @Override public PlatformTransactionManager annotationDrivenTransactionManager() { return txManager(); } }
This approach may be desirable simply because it is more explicit, or it may be necessary in order to distinguish between two
PlatformTransactionManager
beans present in the same container. As the name suggests, the
annotationDrivenTransactionManager()
will be the one used for processing
@Transactional
methods. See TransactionManagementConfigurer Javadoc for further details.
The
#mode
attribute controls how advice is applied: If the mode is
AdviceMode#PROXY
(the default), then the other attributes control the behavior of the proxying. Please note that proxy mode allows for interception of calls through the proxy only; local calls within the same class cannot get intercepted that way.
Note that if the
#mode
is set to
AdviceMode#ASPECTJ
, then the value of the
#proxyTargetClass
attribute will be ignored. Note also that in this case the
spring-aspects
module JAR must be present on the classpath, with compile-time weaving or load-time weaving applying the aspect to the affected classes. There is no proxy involved in such a scenario; local calls will be intercepted as well.
Adding this annotation to an
@Configuration
class imports the Spring Web Reactive configuration from WebFluxConfigurationSupport, e.g.:
@Configuration @EnableWebFlux @ComponentScan(basePackageClasses = MyConfiguration.class) public class MyConfiguration { }
To customize the imported configuration implement WebFluxConfigurer and override individual methods as shown below:
@Configuration @EnableWebFlux @ComponentScan(basePackageClasses = MyConfiguration.class) public class MyConfiguration implements WebFluxConfigurer { @Override public void addFormatters(FormatterRegistry formatterRegistry) { formatterRegistry.addConverter(new MyConverter()); } @Override public void configureMessageWriters(List<HttpMessageWriter<?>> messageWriters) { messageWriters.add(new MyHttpMessageWriter()); } }
Note:
only one
@Configuration
class may have the
@EnableWebFlux
annotation to import the Spring WebFlux configuration. There can however be multiple
@Configuration
classes implementing
WebFluxConfigurer
in order to customize the provided configuration.
If WebFluxConfigurer does not expose some more advanced setting that needs to be configured consider removing the
@EnableWebFlux
annotation and extending directly from WebFluxConfigurationSupport or DelegatingWebFluxConfiguration if you still want to allow WebFluxConfigurer instances to customize the configuration.
Adding this annotation to an
@Configuration
class imports the Spring MVC configuration from WebMvcConfigurationSupport, e.g.:
@Configuration @EnableWebMvc @ComponentScan(basePackageClasses = MyConfiguration.class) public class MyConfiguration { }
To customize the imported configuration, implement the interface WebMvcConfigurer and override individual methods, e.g.:
@Configuration @EnableWebMvc @ComponentScan(basePackageClasses = MyConfiguration.class) public class MyConfiguration implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry formatterRegistry) { formatterRegistry.addConverter(new MyConverter()); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(new MyHttpMessageConverter()); } }
Note:
only one
@Configuration
class may have the
@EnableWebMvc
annotation to import the Spring Web MVC configuration. There can however be multiple
@Configuration
classes implementing
WebMvcConfigurer
in order to customize the provided configuration.
If WebMvcConfigurer does not expose some more advanced setting that needs to be configured consider removing the
@EnableWebMvc
annotation and extending directly from WebMvcConfigurationSupport or DelegatingWebMvcConfiguration, e.g.:
@Configuration @ComponentScan(basePackageClasses = { MyConfiguration.class }) public class MyConfiguration extends WebMvcConfigurationSupport { @Override public void addFormatters(FormatterRegistry formatterRegistry) { formatterRegistry.addConverter(new MyConverter()); } @Bean public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { // Create or delegate to "super" to create and // customize properties of RequestMappingHandlerAdapter } }
org.springframework.web.socket.config.annotation.EnableWebSocket
Add this annotation to an
@Configuration
class to configure processing WebSocket requests:
@Configuration @EnableWebSocket public class MyWebSocketConfig { }
Customize the imported configuration by implementing the WebSocketConfigurer interface:
@Configuration @EnableWebSocket public class MyConfiguration implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(echoWebSocketHandler(), "/echo").withSockJS(); } @Bean public WebSocketHandler echoWebSocketHandler() { return new EchoWebSocketHandler(); } }
org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker
Add this annotation to an
@Configuration
class to enable broker-backed messaging over WebSocket using a higher-level messaging sub-protocol.
@Configuration @EnableWebSocketMessageBroker public class MyWebSocketConfig { }
Customize the imported configuration by implementing the WebSocketMessageBrokerConfigurer interface or more likely extend the convenient base class AbstractWebSocketMessageBrokerConfigurer:
@Configuration @EnableWebSocketMessageBroker public class MyConfiguration extends AbstractWebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/portfolio").withSockJS(); } @Bean public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableStompBrokerRelay("/queue/", "/topic/"); registry.setApplicationDestinationPrefixes("/app/"); } }
org.springframework.test.context.junit.jupiter.EnabledIf
@EnabledIf
is used to signal that the annotated test class or test method is
enabled
and should be executed if the supplied
#expression
evaluates to
true
.
When applied at the class level, all test methods within that class are automatically enabled by default as well.
For basic examples, see the Javadoc for
#expression
.
This annotation may be used as a
meta-annotation
to create custom
composed annotations
. For example, a custom
@EnabledOnMac
annotation can be created as follows.
@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @EnabledIf( expression = "#{systemProperties['os.name'].toLowerCase().contains('mac')}", reason = "Enabled on Mac OS" ) public @interface EnabledOnMac {}
org.springframework.orm.jpa.EntityManagerHolder
Holder wrapping a JPA EntityManager. JpaTransactionManager binds instances of this class to the thread, for a given EntityManagerFactory.
Note: This is an SPI class, not intended to be used by applications.
org.springframework.orm.jpa.EntityManagerProxySubinterface of javax.persistence.EntityManager to be implemented by EntityManager proxies. Allows access to the underlying target EntityManager.
This interface is mainly intended for framework usage. Application code should prefer the use of the
javax.persistence.EntityManager#getDelegate()
method to access native functionality of the underlying resource.
A GenericMessage with a Throwable payload.
The payload is typically a org.springframework.messaging.MessagingException with the message at the point of failure in its
failedMessage
property. An optional
originalMessage
may be provided, which represents the message that existed at the point in the stack where the error message is created.
Consider some code that starts with a message, invokes some process that performs transformation on that message and then fails for some reason, throwing the exception. The exception is caught and an error message produced that contains both the original message, and the transformed message that failed.
org.springframework.web.method.annotation.ErrorsMethodArgumentResolverResolves Errors method arguments.
An
Errors
method argument is expected to appear immediately after the model attribute in the method signature. It is resolved by expecting the last two attributes added to the model to be the model attribute and its BindingResult.
The
<errors>
tag renders field errors in an HTML 'span' tag. Displays errors for either an object or a particular field.
This tag supports three main usage patterns:
path
' to the field name (or path)
path
'
path
' to '
*
'
cssClass
false
HTML Optional Attribute
cssStyle
false
HTML Optional Attribute
delimiter
false
Delimiter for displaying multiple error messages. Defaults to the br tag.
false
HTML Standard Attribute
element
false
Specifies the HTML element that is used to render the enclosing errors.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
false
HTML Standard Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
false
Path to errors object for data binding
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
org.springframework.web.servlet.tags.EscapeBodyTag
The
<escapeBody>
tag is used to escape its enclosed body content, applying HTML escaping and/or JavaScript escaping.
Provides a "htmlEscape" property for explicitly specifying whether to apply HTML escaping. If not set, a page-level default (e.g. from the HtmlEscapeTag) or an application-wide default (the "defaultHtmlEscape" context-param in web.xml) is used.
Provides a "javaScriptEscape" property for specifying whether to apply JavaScript escaping. Can be combined with HTML escaping or used standalone.
Attribute Summary Attribute Required? Runtime Expression? Description htmlEscape false true Set HTML escaping for this tag, as boolean value. Overrides the default HTML escaping setting for the current page. javaScriptEscape false true Set JavaScript escaping for this tag, as boolean value. Default is false. org.springframework.web.bind.EscapedErrors
Errors wrapper that adds automatic HTML escaping to the wrapped instance, for convenient usage in HTML views. Can be retrieved easily via RequestContext's
getErrors
method.
Note that BindTag does not use this class to avoid unnecessary creation of ObjectError instances. It just escapes the messages and values that get copied into the respective BindStatus instance.
org.springframework.web.servlet.tags.EvalTag
The
<eval>
tag evaluates a Spring expression (SpEL) and either prints the result or assigns it to a variable. Supports the standard JSP evaluation context consisting of implicit variables and scoped attributes. Attribute Summary Attribute Required? Runtime Expression? Description expression true true The expression to evaluate. htmlEscape false true Set HTML escaping for this tag, as a boolean value. Overrides the default HTML escaping setting for the current page. javaScriptEscape false true Set JavaScript escaping for this tag, as a boolean value. Default is false. scope false true The scope for the var. 'application', 'session', 'request' and 'page' scopes are supported. Defaults to page scope. This attribute has no effect unless the var attribute is also defined. var false true The name of the variable to export the evaluation result to. If not specified the evaluation result is converted to a String and written as output.
Annotation that marks a method as a listener for application events.
If an annotated method supports a single event type, the method may declare a single parameter that reflects the event type to listen to. If an annotated method supports multiple event types, this annotation may refer to one or more supported event types using the
classes
attribute. See the
#classes
javadoc for further details.
Events can be ApplicationEvent instances as well as arbitrary objects.
Processing of
@EventListener
annotations is performed via the internal EventListenerMethodProcessor bean which gets registered automatically when using Java config or manually via the
<context:annotation-config/>
or
<context:component-scan/>
element when using XML config.
Annotated methods may have a non-
void
return type. When they do, the result of the method invocation is sent as a new event. If the return type is either an array or a collection, each element is sent as a new individual event.
It is also possible to define the order in which listeners for a certain event are to be invoked. To do so, add Spring's common org.springframework.core.annotation.Order annotation alongside this event listener annotation.
While it is possible for an event listener to declare that it throws arbitrary exception types, any checked exceptions thrown from an event listener will be wrapped in an java.lang.reflect.UndeclaredThrowableException since the event publisher can only handle runtime exceptions.
org.springframework.context.event.EventPublicationInterceptor
MethodInterceptor that publishes an
ApplicationEvent
to all
ApplicationListeners
registered with an
ApplicationEventPublisher
after each
successful
method invocation.
Note that this interceptor is only capable of publishing
stateless
events configured via the
"applicationEventClass"
property.
Annotation for handling exceptions in specific handler classes and/or handler methods.
Handler methods which are annotated with this annotation are allowed to have very flexible signatures. They may have parameters of the following types, in arbitrary order:
#value()
.
null
.
Note that session access may not be thread-safe, in particular in a Servlet environment: Consider switching the
"synchronizeOnSession"
flag to "true" if multiple requests are allowed to access a session concurrently.
The following return types are supported for handler methods:
ModelAndView
object (from Servlet MVC).
void
if the method handles the response itself (by writing the response content directly, declaring an argument of type javax.servlet.ServletResponse / javax.servlet.http.HttpServletResponse for that purpose) or if the view name is supposed to be implicitly determined through a org.springframework.web.servlet.RequestToViewNameTranslator (not declaring a response argument in the handler method signature).
In Servlet environments, you can combine the
ExceptionHandler
annotation with ResponseStatus, to define the response status for the HTTP response.
Container for request and response details for exchanges performed through WebTestClient.
Note that a decoded response body is not exposed at this level since the body may not have been decoded and consumed yet. Sub-types EntityExchangeResult and FluxExchangeResult provide access to a decoded response entity and a decoded (but not consumed) response body respectively.
org.springframework.messaging.support.ExecutorChannelInterceptorAn extension of ChannelInterceptor with callbacks to intercept the asynchronous sending of a org.springframework.messaging.Message to a specific subscriber through an java.util.concurrent.Executor. Supported on org.springframework.messaging.MessageChannel implementations that can be configured with an Executor.
org.springframework.core.task.support.ExecutorServiceAdapter
Adapter that takes a Spring org.springframework.core.task.TaskExecutor) and exposes a full
java.util.concurrent.ExecutorService
for it.
This is primarily for adapting to client components that communicate via the
java.util.concurrent.ExecutorService
API. It can also be used as common ground between a local Spring
TaskExecutor
backend and a JNDI-located
ManagedExecutorService
in a Java EE 6 environment.
NOTE:
This ExecutorService adapter does
not
support the lifecycle methods in the
java.util.concurrent.ExecutorService
API ("shutdown()" etc), similar to a server-wide
ManagedExecutorService
in a Java EE 6 environment. The lifecycle is always up to the backend pool, with this adapter acting as an access-only proxy for that target pool.
Simple extension of the JndiTemplate class that always returns a given object.
Very useful for testing. Effectively a mock object.
org.springframework.util.backoff.ExponentialBackOff
Implementation of BackOff that increases the back off period for each retry attempt. When the interval has reached the
max interval
, it is no longer increased. Stops retrying once the
max elapsed time
has been reached.
Example: The default interval is {@value #DEFAULT_INITIAL_INTERVAL} ms, the default multiplier is {@value #DEFAULT_MULTIPLIER}, and the default max interval is {@value #DEFAULT_MAX_INTERVAL}. For 10 attempts the sequence will be as follows:
request# back off 1 2000 2 3000 3 4500 4 6750 5 10125 6 15187 7 22780 8 30000 9 30000 10 30000
Note that the default max elapsed time is
Long#MAX_VALUE
. Use
#setMaxElapsedTime(long)
to limit the maximum length of time that an instance should accumulate before returning
BackOffExecution#STOP
.
Convenient methods for creating advisors that may be used when autoproxying beans created with the Spring IoC container, binding the bean name to the current invocation. May support a
bean()
pointcut designator with AspectJ.
Typically used in Spring auto-proxying, where the bean name is known at proxy creation time.
org.springframework.aop.interceptor.ExposeInvocationInterceptorInterceptor that exposes the current org.aopalliance.intercept.MethodInvocation as a thread-local object. We occasionally need to do this; for example, when a pointcut (e.g. an AspectJ expression pointcut) needs to know the full invocation context.
Don't use this interceptor unless this is really necessary. Target objects should not normally know about Spring AOP, as this creates a dependency on Spring API. Target objects should be plain POJOs as far as possible.
If used, this interceptor will normally be the first in the interceptor chain.
org.springframework.expression.ExpressionInvocationTargetExceptionThis exception wraps (as cause) a checked exception thrown by some method that SpEL invokes. It differs from a SpelEvaluationException because this indicates the occurrence of a checked exception that the invoked method was defined to throw. SpelEvaluationExceptions are for handling (and wrapping) unexpected exceptions.
org.springframework.web.method.annotation.ExpressionValueMethodArgumentResolver
Resolves method arguments annotated with
@Value
.
An
@Value
does not have a name but gets resolved from the default value string, which may contain ${...} placeholder or Spring Expression Language #{...} expressions.
A WebDataBinder may be invoked to apply type conversion to resolved argument value.
org.springframework.web.reactive.result.method.annotation.ExpressionValueMethodArgumentResolver
Resolves method arguments annotated with
@Value
.
An
@Value
does not have a name but gets resolved from the default value string, which may contain ${...} placeholder or Spring Expression Language #{...} expressions.
BeanInfoFactory implementation that evaluates whether bean classes have "non-standard" JavaBeans setter methods and are thus candidates for introspection by Spring's (package-visible)
ExtendedBeanInfo
implementation.
Ordered at
Ordered#LOWEST_PRECEDENCE
to allow other user-defined BeanInfoFactory types to take precedence.
Delegate for creating a variety of javax.persistence.EntityManager proxies that follow the JPA spec's semantics for "extended" EntityManagers.
Supports several different variants of "extended" EntityManagers: in particular, an "application-managed extended EntityManager", as defined by
javax.persistence.EntityManagerFactory#createEntityManager()
, as well as a "container-managed extended EntityManager", as defined by
javax.persistence.PersistenceContextType#EXTENDED
.
The original difference between "application-managed" and "container-managed" was the need for explicit joining of an externally managed transaction through the
EntityManager#joinTransaction()
method in the "application" case versus the automatic joining on each user-level EntityManager operation in the "container" case. As of JPA 2.1, both join modes are available with both kinds of EntityManagers, so the difference between "application-" and "container-managed" is now primarily in the join mode default and in the restricted lifecycle of a container-managed EntityManager (i.e. tied to the object that it is injected into).
Implementation of ResponseErrorHandler that uses HttpMessageConverters to convert HTTP error responses to RestClientException.
To use this error handler, you must specify a
status mapping
and/or a
series mapping
. If either of these mappings has a match for the
status code
of a given
ClientHttpResponse
,
#hasError(ClientHttpResponse)
will return
true
and
#handleError(ClientHttpResponse)
will attempt to use the
configured message converters
to convert the response into the mapped subclass of RestClientException. Note that the
status mapping
takes precedence over
series mapping
.
If there is no match, this error handler will default to the behavior of DefaultResponseErrorHandler. Note that you can override this default behavior by specifying a
series mapping
from
HttpStatus.Series#CLIENT_ERROR
and/or
HttpStatus.Series#SERVER_ERROR
to
null
.
WebRequest adapter for a JSF javax.faces.context.FacesContext.
Requires JSF 2.0 or higher, as of Spring 4.0.
org.springframework.beans.factory.FactoryBeanNotInitializedException
Exception to be thrown from a FactoryBean's
getObject()
method if the bean is not fully initialized yet, for example because it is involved in a circular reference.
Note: A circular reference with a FactoryBean cannot be solved by eagerly caching singleton instances like with normal beans. The reason is that every FactoryBean needs to be fully initialized before it can return the created bean, while only specific normal beans need to be initialized - that is, if a collaborating bean actually invokes them on initialization instead of just storing the reference.
org.springframework.beans.factory.parsing.FailFastProblemReporterSimple ProblemReporter implementation that exhibits fail-fast behavior when errors are encountered.
The first error encountered results in a BeanDefinitionParsingException being thrown.
Warnings are written to
the log
for this class.
A speedy alternative to java.io.ByteArrayOutputStream. Note that this variant does
not
extend
ByteArrayOutputStream
, unlike its sibling ResizableByteArrayOutputStream.
Unlike java.io.ByteArrayOutputStream, this implementation is backed by a java.util.LinkedList of
byte[]
instead of 1 constantly resizing
byte[]
. It does not copy buffers when it gets expanded.
The initial buffer is only created when the stream is first written. There is also no copying of the internal buffer if its contents is extracted with the
#writeTo(OutputStream)
method.
FactoryBean which retrieves a static or non-static field value.
Typically used for retrieving public static final constants. Usage example:
// standard definition for exposing a static field, specifying the "staticField" property <bean id="myField" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"> <property name="staticField" value="java.sql.Connection.TRANSACTION_SERIALIZABLE"/> </bean> // convenience version that specifies a static field pattern as bean name <bean id="java.sql.Connection.TRANSACTION_SERIALIZABLE" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean"/>
If you are using Spring 2.0, you can also use the following style of configuration for public static fields.
<util:constant static-field="java.sql.Connection.TRANSACTION_SERIALIZABLE"/>
org.springframework.util.FileCopyUtils
Simple utility methods for file and stream copying. All copy methods use a block size of 4096 bytes, and close all affected streams when done. A variation of the copy methods from this class that leave streams open can be found in StreamUtils.
Mainly for use within the framework, but also useful for application code.
org.springframework.beans.propertyeditors.FileEditor
Editor for
java.io.File
, to directly populate a File property from a Spring resource location.
Supports Spring-style URL notation: any fully qualified standard URL ("file:", "http:", etc) and Spring's special "classpath:" pseudo-URL.
NOTE: The behavior of this editor has changed in Spring 2.0. Previously, it created a File instance directly from a filename. As of Spring 2.0, it takes a standard Spring resource location as input; this is consistent with URLEditor and InputStreamEditor now.
NOTE: In Spring 2.5 the following modification was made. If a file name is specified without a URL prefix or without an absolute path then we try to locate the file using standard ResourceLoader semantics. If the file was not found, then a File instance is created assuming the file name refers to a relative file location.
org.springframework.core.io.FileSystemResourceLoaderResourceLoader implementation that resolves plain paths as file system resources rather than as class path resources (the latter is DefaultResourceLoader's default strategy).
NOTE: Plain paths will always be interpreted as relative to the current VM working directory, even if they start with a slash. (This is consistent with the semantics in a Servlet container.) Use an explicit "file:" prefix to enforce an absolute file path.
org.springframework.context.support.FileSystemXmlApplicationContext is a full-fledged ApplicationContext implementation that provides the same resource path resolution strategy.
org.springframework.context.support.FileSystemXmlApplicationContextStandalone XML application context, taking the context definition files from the file system or from URLs, interpreting plain paths as relative file system locations (e.g. "mydir/myfile.txt"). Useful for test harnesses as well as for standalone environments.
NOTE: Plain paths will always be interpreted as relative to the current VM working directory, even if they start with a slash. (This is consistent with the semantics in a Servlet container.) Use an explicit "file:" prefix to enforce an absolute file path.
The config location defaults can be overridden via
#getConfigLocations
, Config locations can either denote concrete files like "/myfiles/context.xml" or Ant-style patterns like "/myfiles/*-context.xml" (see the org.springframework.util.AntPathMatcher javadoc for pattern details).
Note: In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra XML file.
This is a simple, one-stop shop convenience ApplicationContext. Consider using the GenericApplicationContext class in combination with an org.springframework.beans.factory.xml.XmlBeanDefinitionReader for more flexible context setup.
org.springframework.core.io.FileUrlResourceSubclass of UrlResource which assumes file resolution, to the degree of implementing the WritableResource interface for it.
This is the class resolved by DefaultResourceLoader for a "file:..." URL location, allowing a downcast to WritableResource for it.
Alternatively, for direct construction from a java.io.File handle, consider using FileSystemResource. For an NIO java.nio.file.Path, consider using PathResource instead.
org.springframework.web.server.i18n.FixedLocaleContextResolverLocaleContextResolver implementation that always returns a fixed default locale and optionally time zone. Default is the current JVM's default locale.
Note: Does not support
setLocale(Context)
, as the fixed locale and time zone cannot be changed.
org.springframework.web.servlet.LocaleResolver implementation that always returns a fixed default locale and optionally time zone. Default is the current JVM's default locale.
Note: Does not support
setLocale(Context)
, as the fixed locale and time zone cannot be changed.
org.springframework.web.servlet.ThemeResolver implementation that simply uses a fixed theme. The fixed name can be defined via the "defaultThemeName" property; out of the box, it is "theme".
Note: Does not support
setThemeName
, as the fixed theme cannot be changed.
A
VersionStrategy
that relies on a fixed version applied as a request path prefix, e.g. reduced SHA, version name, release date, etc.
This is useful for example when ContentVersionStrategy cannot be used such as when using JavaScript module loaders which are in charge of loading the JavaScript resources and need to know their relative paths.
org.springframework.web.servlet.resource.FixedVersionStrategy
A
VersionStrategy
that relies on a fixed version applied as a request path prefix, e.g. reduced SHA, version name, release date, etc.
This is useful for example when ContentVersionStrategy cannot be used such as when using JavaScript module loaders which are in charge of loading the JavaScript resources and need to know their relative paths.
org.springframework.test.web.servlet.result.FlashAttributeResultMatchersFactory for "output" flash attribute assertions.
An instance of this class is typically accessed via
MockMvcResultMatchers#flash
.
A Spring FactoryBean that builds and exposes a preconfigured ForkJoinPool.
For details on the ForkJoinPool API and its use with RecursiveActions, see the JDK 7 javadoc .
jsr166.jar
, containing
java.util.concurrent
updates for Java 6, can be obtained from the
concurrency interest website
.
A factory providing convenient access to a
FormattingConversionService
configured with converters and formatters for common types such as numbers and datetimes.
Additional converters and formatters can be registered declaratively through
#setConverters(Set)
and
#setFormatters(Set)
. Another option is to register converters and formatters in code by implementing the FormatterRegistrar interface. You can then configure provide the set of registrars to use through
#setFormatterRegistrars(Set)
.
A good example for registering converters and formatters in code is
JodaTimeFormatterRegistrar
, which registers a number of date-related formatters and converters. For a more detailed list of cases see
#setFormatterRegistrars(Set)
Like all
FactoryBean
implementations, this class is suitable for use when configuring a Spring application context using Spring
<beans>
XML. When configuring the container with org.springframework.context.annotation.Configuration classes, simply instantiate, configure and return the appropriate
FormattingConversionService
object from a org.springframework.context.annotation.Bean method.
Extract values from "Forwarded" and "X-Forwarded-*" headers in order to wrap and override the following from the request and response:
getServerName()
,
getServerPort()
,
getScheme()
,
isSecure()
, and
sendRedirect(String)
. In effect the wrapped request and response reflect the client-originated protocol and address.
Note:
This filter can also be used in a
removeOnly
mode where "Forwarded" and "X-Forwarded-*" headers are only eliminated without being used.
Extract values from "Forwarded" and "X-Forwarded-*" headers in order to change and override
ServerHttpRequest#getURI()
. In effect the request URI will reflect the client-originated protocol and address.
Note:
This filter can also be used in a
removeOnly
mode where "Forwarded" and "X-Forwarded-*" headers are only eliminated without being used.
Factory that configures a FreeMarker Configuration. Can be used standalone, but typically you will either use FreeMarkerConfigurationFactoryBean for preparing a Configuration as bean reference, or FreeMarkerConfigurer for web views.
The optional "configLocation" property sets the location of a FreeMarker properties file, within the current application. FreeMarker properties can be overridden via "freemarkerSettings". All of these properties will be set by calling FreeMarker's
Configuration.setSettings()
method and are subject to constraints set by FreeMarker.
The "freemarkerVariables" property can be used to specify a Map of shared variables that will be applied to the Configuration via the
setAllSharedVariables()
method. Like
setSettings()
, these entries are subject to FreeMarker constraints.
The simplest way to use this class is to specify a "templateLoaderPath"; FreeMarker does not need any further configuration then.
Note: Spring's FreeMarker support requires FreeMarker 2.3 or higher.
org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBeanFactory bean that creates a FreeMarker Configuration and provides it as bean reference. This bean is intended for any kind of usage of FreeMarker in application code, e.g. for generating email content. For web views, FreeMarkerConfigurer is used to set up a FreeMarkerConfigurationFactory. The simplest way to use this class is to specify just a "templateLoaderPath"; you do not need any further configuration then. For example, in a web application context:
<bean id="freemarkerConfiguration" class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean"> <property name="templateLoaderPath" value="/WEB-INF/freemarker/"/> </bean>
See the base class FreeMarkerConfigurationFactory for configuration details.
Note: Spring's FreeMarker support requires FreeMarker 2.3 or higher.
org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurerJavaBean to configure FreeMarker for web usage, via the "configLocation" and/or "freemarkerSettings" and/or "templateLoaderPath" properties. The simplest way to use this class is to specify just a "templateLoaderPath"; you do not need any further configuration then.
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath"><value>/WEB-INF/freemarker/</value></property> </bean>
This bean must be included in the application context of any application using Spring's FreeMarkerView for web MVC. It exists purely to configure FreeMarker. It is not meant to be referenced by application components but just internally by FreeMarkerView. Implements FreeMarkerConfig to be found by FreeMarkerView without depending on the bean name the configurer. Each DispatcherServlet can define its own FreeMarkerConfigurer if desired.
Note that you can also refer to a preconfigured FreeMarker Configuration instance, for example one set up by FreeMarkerConfigurationFactoryBean, via the "configuration" property. This allows to share a FreeMarker Configuration for web and email usage, for example.
This configurer registers a template loader for this package, allowing to reference the "spring.ftl" macro library (contained in this package and thus in spring.jar) like this:
<#import "/spring.ftl" as spring/> <@spring.bind "person.age"/> age is ${spring.status.value}
Note: Spring's FreeMarker support requires FreeMarker 2.3 or higher.
org.springframework.web.reactive.result.view.freemarker.FreeMarkerView
A
View
implementation that uses the FreeMarker template engine.
Depends on a single FreeMarkerConfig object such as FreeMarkerConfigurer being accessible in the application context. Alternatively set the FreeMarker configuration can be set directly on this class via
#setConfiguration
.
The
url
property is the location of the FreeMarker template relative to the FreeMarkerConfigurer's
templateLoaderPath
.
Note: Spring's FreeMarker support requires FreeMarker 2.3 or higher.
org.springframework.web.reactive.result.view.freemarker.FreeMarkerViewResolver
A
ViewResolver
for resolving FreeMarkerView instances, i.e. FreeMarker templates and custom subclasses of it.
The view class for all views generated by this resolver can be specified via the "viewClass" property. See UrlBasedViewResolver for details.
org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolverConvenience subclass of org.springframework.web.servlet.view.UrlBasedViewResolver that supports FreeMarkerView (i.e. FreeMarker templates) and custom subclasses of it.
The view class for all views generated by this resolver can be specified via the "viewClass" property. See UrlBasedViewResolver's javadoc for details.
Note: When chaining ViewResolvers, a FreeMarkerViewResolver will check for the existence of the specified template resources and only return a non-null View object if the template was actually found.
org.springframework.expression.spel.ast.FunctionReferenceA function reference is of the form "#someFunction(a,b,c)". Functions may be defined in the context prior to the expression being evaluated or within the expression itself using a lambda function definition. For example: Lambda function definition in an expression: "(#max = {|x,y|$x>$y?$x:$y};max(2,3))" Calling context defined function: "#isEven(37)". Functions may also be static java methods, registered in the context prior to invocation of the expression.
Functions are very simplistic, the arguments are not part of the definition (right now), so the names must be unique.
org.springframework.jdbc.support.GeneratedKeyHolderDefault implementation of the KeyHolder interface, to be used for holding auto-generated keys (as potentially returned by JDBC insert statements).
Create an instance of this class for each insert operation, and pass it to the corresponding org.springframework.jdbc.core.JdbcTemplate or {org.springframework.jdbc.object.SqlUpdate} methods.
org.springframework.beans.factory.support.GenericBeanDefinitionGenericBeanDefinition is a one-stop shop for standard bean definition purposes. Like any bean definition, it allows for specifying a class plus optionally constructor argument values and property values. Additionally, deriving from a parent bean definition can be flexibly configured through the "parentName" property.
In general, use this
GenericBeanDefinition
class for the purpose of registering user-visible bean definitions (which a post-processor might operate on, potentially even reconfiguring the parent name). Use
RootBeanDefinition
/
ChildBeanDefinition
where parent/child relationships happen to be pre-determined.
An org.springframework.context.ApplicationContext implementation that extends GenericApplicationContext and implements GroovyObject such that beans can be retrieved with the dot de-reference syntax instead of using
#getBean
.
Consider this as the equivalent of GenericXmlApplicationContext for Groovy bean definitions, or even an upgrade thereof since it seamlessly understands XML bean definition files as well. The main difference is that, within a Groovy script, the context can be used with an inline bean definition closure as follows:
import org.hibernate.SessionFactory import org.apache.commons.dbcp.BasicDataSource def context = new GenericGroovyApplicationContext() context.reader.beans { dataSource(BasicDataSource) { // <--- invokeMethod driverClassName = "org.hsqldb.jdbcDriver" url = "jdbc:hsqldb:mem:grailsDB" username = "sa" // <-- setProperty password = "" settings = [mynew:"setting"] } sessionFactory(SessionFactory) { dataSource = dataSource // <-- getProperty for retrieving references } myService(MyService) { nestedBean = { AnotherBean bean -> // <-- setProperty with closure for nested bean dataSource = dataSource } } } context.refresh()
Alternatively, load a Groovy bean definition script like the following from an external resource (e.g. an "applicationContext.groovy" file):
import org.hibernate.SessionFactory import org.apache.commons.dbcp.BasicDataSource beans { dataSource(BasicDataSource) { driverClassName = "org.hsqldb.jdbcDriver" url = "jdbc:hsqldb:mem:grailsDB" username = "sa" password = "" settings = [mynew:"setting"] } sessionFactory(SessionFactory) { dataSource = dataSource } myService(MyService) { nestedBean = { AnotherBean bean -> dataSource = dataSource } } }
With the following Java code creating the
GenericGroovyApplicationContext
(potentially using Ant-style '*'/'**' location patterns):
GenericGroovyApplicationContext context = new GenericGroovyApplicationContext(); context.load("org/myapp/applicationContext.groovy"); context.refresh();
Or even more concise, provided that no extra configuration is needed:
ApplicationContext context = new GenericGroovyApplicationContext("org/myapp/applicationContext.groovy");
This application context also understands XML bean definition files, allowing for seamless mixing and matching with Groovy bean definition files. ".xml" files will be parsed as XML content; all other kinds of resources will be parsed as Groovy scripts.
org.springframework.test.context.support.GenericGroovyXmlContextLoaderConcrete implementation of AbstractGenericContextLoader that reads bean definitions from Groovy scripts and XML configuration files.
Default resource locations are detected using the suffixes
"-context.xml"
and
"Context.groovy"
.
Concrete implementation of AbstractGenericWebContextLoader that loads bean definitions from Groovy scripts and XML configuration files.
Default resource locations are detected using the suffixes
"-context.xml"
and
"Context.groovy"
.
An extension of the SimpleMessageConverter that uses a ConversionService to convert the payload of the message to the requested type.
Return
null
if the conversion service cannot convert from the payload type to the requested type.
Generic implementation of the JCA 1.7 javax.resource.spi.endpoint.MessageEndpointFactory interface, providing transaction management capabilities for any kind of message listener object (e.g. javax.jms.MessageListener objects or javax.resource.cci.MessageListener objects.
Uses AOP proxies for concrete endpoint instances, simply wrapping the specified message listener object and exposing all of its implemented interfaces on the endpoint instance.
Typically used with Spring's GenericMessageEndpointManager, but not tied to it. As a consequence, this endpoint factory could also be used with programmatic endpoint management on a native javax.resource.spi.ResourceAdapter instance.
org.springframework.jdbc.object.GenericStoredProcedureConcrete implementation making it possible to define the RDBMS stored procedures in an application context without writing a custom Java implementation class.
This implementation does not provide a typed method for invocation so executions must use one of the generic
StoredProcedure#execute(java.util.Map)
or
StoredProcedure#execute(org.springframework.jdbc.core.ParameterMapper)
methods.
Basic AutowireCandidateResolver that performs a full generic type match with the candidate's type if the dependency is declared as a generic type (e.g. Repository<Customer>).
This is the base class for org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolver, providing an implementation all non-annotation-based resolution steps at this level.
org.springframework.core.GenericTypeResolverHelper class for resolving generic types against type variables.
Mainly intended for usage within the framework, resolving method parameter types even when they are declared generically.
org.springframework.context.support.GenericXmlApplicationContext
Convenient application context with built-in XML support. This is a flexible alternative to ClassPathXmlApplicationContext and FileSystemXmlApplicationContext, to be configured via setters, with an eventual
#refresh()
call activating the context.
In case of multiple configuration files, bean definitions in later files will override those defined in earlier files. This can be leveraged to intentionally override certain bean definitions via an extra configuration file appended to the list.
org.springframework.web.bind.annotation.GetMapping
Annotation for mapping HTTP
GET
requests onto specific handler methods.
Specifically,
@GetMapping
is a
composed annotation
that acts as a shortcut for
@RequestMapping(method = RequestMethod.GET)
.
LoadTimeWeaver implementation for GlassFish's
org.glassfish.api.deployment.InstrumentableClassLoader InstrumentableClassLoader
.
As of Spring Framework 5.0, this weaver supports GlassFish 4+.
org.springframework.beans.factory.groovy.GroovyBeanDefinitionReaderA Groovy-based reader for Spring bean definitions: like a Groovy builder, but more of a DSL for Spring configuration.
This bean definition reader also understands XML bean definition files, allowing for seamless mixing and matching with Groovy bean definition files.
Typically applied to a org.springframework.beans.factory.support.DefaultListableBeanFactory or a org.springframework.context.support.GenericApplicationContext, but can be used against any BeanDefinitionRegistry implementation.
Example Syntax import org.hibernate.SessionFactory import org.apache.commons.dbcp.BasicDataSource def reader = new GroovyBeanDefinitionReader(myApplicationContext) reader.beans { dataSource(BasicDataSource) { // <--- invokeMethod driverClassName = "org.hsqldb.jdbcDriver" url = "jdbc:hsqldb:mem:grailsDB" username = "sa" // <-- setProperty password = "" settings = [mynew:"setting"] } sessionFactory(SessionFactory) { dataSource = dataSource // <-- getProperty for retrieving references } myService(MyService) { nestedBean = { AnotherBean bean -> // <-- setProperty with closure for nested bean dataSource = dataSource } } }
You can also load resources containing beans defined in a Groovy script using either the
#loadBeanDefinitions(Resource...)
or
#loadBeanDefinitions(String...)
method, with a script looking similar to the following.
import org.hibernate.SessionFactory import org.apache.commons.dbcp.BasicDataSource beans { dataSource(BasicDataSource) { driverClassName = "org.hsqldb.jdbcDriver" url = "jdbc:hsqldb:mem:grailsDB" username = "sa" password = "" settings = [mynew:"setting"] } sessionFactory(SessionFactory) { dataSource = dataSource } myService(MyService) { nestedBean = { AnotherBean bean -> dataSource = dataSource } } }
org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer
An extension of Groovy's groovy.text.markup.TemplateConfiguration and an implementation of Spring MVC's GroovyMarkupConfig for creating a
MarkupTemplateEngine
for use in a web application. The most basic way to configure this class is to set the "resourceLoaderPath". For example:
// Add the following to an @Configuration class @Bean public GroovyMarkupConfig groovyMarkupConfigurer() { GroovyMarkupConfigurer configurer = new GroovyMarkupConfigurer(); configurer.setResourceLoaderPath("classpath:/WEB-INF/groovymarkup/"); return configurer; }
By default this bean will create a MarkupTemplateEngine with:
This bean must be included in the application context of any application using the Spring MVC GroovyMarkupView for rendering. It exists purely for the purpose of configuring Groovy's Markup templates. It is not meant to be referenced by application components directly. It implements GroovyMarkupConfig to be found by GroovyMarkupView without depending on a bean name. Each DispatcherServlet can define its own GroovyMarkupConfigurer if desired.
Note that resource caching is enabled by default in MarkupTemplateEngine. Use the
#setCacheTemplates(boolean)
to configure that as necessary.
Spring's Groovy Markup template support requires Groovy 2.3.1 or higher.
org.springframework.web.servlet.view.groovy.GroovyMarkupViewAn AbstractTemplateView subclass based on Groovy XML/XHTML markup templates.
Spring's Groovy Markup Template support requires Groovy 2.3.1 and higher.
org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolverConvenience subclass of @link AbstractTemplateViewResolver} that supports GroovyMarkupView (i.e. Groovy XML/XHTML markup templates) and custom subclasses of it.
The view class for all views created by this resolver can be specified via the
#setViewClass(Class)
property.
Note: When chaining ViewResolvers this resolver will check for the existence of the specified template resources and only return a non-null View object if a template is actually found.
org.springframework.scripting.groovy.GroovyScriptFactoryorg.springframework.scripting.ScriptFactory implementation for a Groovy script.
Typically used in combination with a org.springframework.scripting.support.ScriptFactoryPostProcessor; see the latter's javadoc for a configuration example.
Note: Spring 4.0 supports Groovy 1.8 and higher.
org.springframework.web.context.support.GroovyWebApplicationContextorg.springframework.web.context.WebApplicationContext implementation which takes its configuration from Groovy bean definition scripts and/or XML files, as understood by an org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader. This is essentially the equivalent of org.springframework.context.support.GenericGroovyApplicationContext for a web environment.
By default, the configuration will be taken from "/WEB-INF/applicationContext.groovy" for the root context, and "/WEB-INF/test-servlet.groovy" for a context with the namespace "test-servlet" (like for a DispatcherServlet instance with the servlet-name "test").
The config location defaults can be overridden via the "contextConfigLocation" context-param of org.springframework.web.context.ContextLoader and servlet init-param of org.springframework.web.servlet.FrameworkServlet. Config locations can either denote concrete files like "/WEB-INF/context.groovy" or Ant-style patterns like "/WEB-INF/*-context.groovy" (see org.springframework.util.PathMatcher javadoc for pattern details). Note that ".xml" files will be parsed as XML content; all other kinds of resources will be parsed as Groovy scripts.
Note: In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra Groovy script.
For a WebApplicationContext that reads in a different bean definition format, create an analogous subclass of AbstractRefreshableWebApplicationContext. Such a context implementation can be specified as "contextClass" context-param for ContextLoader or "contextClass" init-param for FrameworkServlet.
org.springframework.http.converter.json.GsonHttpMessageConverterImplementation of org.springframework.http.converter.HttpMessageConverter that can read and write JSON using the Google Gson library.
This converter can be used to bind to typed beans or untyped
HashMap
s. By default, it supports
application/json
and
application/*+json
with
UTF-8
character set.
Tested against Gson 2.6; compatible with Gson 2.0 and higher.
org.springframework.web.reactive.resource.GzipResourceResolver
A
ResourceResolver
that delegates to the chain to locate a resource and then attempts to find a variation with the ".gz" extension.
The resolver gets involved only if the "Accept-Encoding" request header contains the value "gzip" indicating the client accepts gzipped responses.
org.springframework.web.servlet.resource.GzipResourceResolver
A
ResourceResolver
that delegates to the chain to locate a resource and then attempts to find a variation with the ".gz" extension.
The resolver gets involved only if the "Accept-Encoding" request header contains the value "gzip" indicating the client accepts gzipped responses.
org.springframework.messaging.handler.invocation.HandlerMethodReturnValueHandlerCompositeA HandlerMethodReturnValueHandler that wraps and delegates to others.
org.springframework.test.web.servlet.result.HandlerResultMatchersFactory for assertions on the selected handler or handler method.
An instance of this class is typically accessed via
MockMvcResultMatchers#handler
.
Note: Expectations that assert the controller method used to process the request work only for requests processed with RequestMappingHandlerMapping and RequestMappingHandlerAdapter which is used by default with the Spring MVC Java config and XML namespace.
org.springframework.web.socket.server.HandshakeFailureExceptionThrown when handshake processing failed to complete due to an internal, unrecoverable error. This implies a server error (HTTP status code 500) as opposed to a failure in the handshake negotiation.
By contrast, when handshake negotiation fails, the response status code will be 200 and the response headers and body will have been updated to reflect the cause for the failure. A HandshakeHandler implementation will have protected methods to customize updates to the response in those cases.
org.springframework.test.web.servlet.result.HeaderResultMatchersFactory for response header assertions.
An instance of this class is available via
MockMvcResultMatchers#header
.
Resolves the following method parameters:
org.aopalliance.intercept.MethodInterceptor for accessing a Hessian service. Supports authentication via username and password. The service URL must be an HTTP URL exposing a Hessian service.
Hessian is a slim, binary RPC protocol. For information on Hessian, see the Hessian website Note: As of Spring 4.0, this client requires Hessian 4.0 or above.
Note: There is no requirement for services accessed with this proxy factory to have been exported using Spring's HessianServiceExporter, as there is no special handling involved. As a consequence, you can also access services that have been exported using Caucho's com.caucho.hessian.server.HessianServlet.
org.springframework.remoting.caucho.HessianExporterGeneral stream-based protocol exporter for a Hessian endpoint.
Hessian is a slim, binary RPC protocol. For information on Hessian, see the Hessian website . Note: As of Spring 4.0, this exporter requires Hessian 4.0 or above.
org.springframework.remoting.caucho.HessianProxyFactoryBeanFactoryBean for Hessian proxies. Exposes the proxied service for use as a bean reference, using the specified service interface.
Hessian is a slim, binary RPC protocol. For information on Hessian, see the Hessian website Note: As of Spring 4.0, this proxy factory requires Hessian 4.0 or above.
The service URL must be an HTTP URL exposing a Hessian service. For details, see the HessianClientInterceptor javadoc.
org.springframework.remoting.caucho.HessianServiceExporterServlet-API-based HTTP request handler that exports the specified service bean as Hessian service endpoint, accessible via a Hessian proxy.
Note: Spring also provides an alternative version of this exporter, for Sun's JRE 1.6 HTTP server: SimpleHessianServiceExporter.
Hessian is a slim, binary RPC protocol. For information on Hessian, see the Hessian website . Note: As of Spring 4.0, this exporter requires Hessian 4.0 or above.
Hessian services exported with this class can be accessed by any Hessian client, as there isn't any special handling involved.
org.springframework.orm.hibernate5.support.HibernateDaoSupportConvenient super class for Hibernate-based data access objects.
Requires a SessionFactory to be set, providing a org.springframework.orm.hibernate5.HibernateTemplate based on it to subclasses through the
#getHibernateTemplate()
method. Can alternatively be initialized directly with a HibernateTemplate, in order to reuse the latter's settings such as the SessionFactory, exception translator, flush mode, etc.
This class will create its own HibernateTemplate instance if a SessionFactory is passed in. The "allowCreate" flag on that HibernateTemplate will be "true" by default. A custom HibernateTemplate instance can be used through overriding
#createHibernateTemplate
.
NOTE: Hibernate access code can also be coded in plain Hibernate style. Hence, for newly started projects, consider adopting the standard Hibernate style of coding data access objects instead, based on
SessionFactory#getCurrentSession()
. This HibernateTemplate primarily exists as a migration helper for Hibernate 3 based data access code, to benefit from bug fixes in Hibernate 5.x.
Simple
FactoryBean
that exposes the underlying SessionFactory behind a Hibernate-backed JPA EntityManagerFactory.
Primarily available for resolving a SessionFactory by JPA persistence unit name via the
"persistenceUnitName"
bean property.
Note that, for straightforward cases, you could also simply declare a factory method:
<bean id="sessionFactory" factory-bean="entityManagerFactory" factory-method="getSessionFactory"/>
And as of JPA 2.1,
EntityManagerFactory#unwrap
provides a nice approach as well, in particular within configuration class arrangements:
@Bean public SessionFactory sessionFactory(@Qualifier("entityManagerFactory") EntityManagerFactory emf) { return emf.unwrap(SessionFactory.class); }
Please note: Since Hibernate 5.2 changed its
SessionFactory
interface to extend JPA's
EntityManagerFactory
, you may get conflicts when injecting by type, with both the original factory and your custom
SessionFactory
matching
EntityManagerFactory
. An explicit qualifier for the original factory (as indicated above) is recommended here.
org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter
org.springframework.orm.jpa.JpaVendorAdapter implementation for Hibernate EntityManager. Developed and tested against Hibernate 5.0, 5.1 and 5.2; backwards-compatible with Hibernate 4.3 at runtime on a best-effort basis.
Exposes Hibernate's persistence provider and EntityManager extension interface, and adapts AbstractJpaVendorAdapter's common configuration settings. Also supports the detection of annotated packages (through
org.springframework.orm.jpa.persistenceunit.SmartPersistenceUnitInfo#getManagedPackages()
), e.g. containing Hibernate org.hibernate.annotations.FilterDef annotations, along with Spring-driven entity scanning which requires no
persistence.xml
(
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean#setPackagesToScan
).
org.springframework.transaction.PlatformTransactionManager implementation for a single Hibernate SessionFactory. Binds a Hibernate Session from the specified factory to the thread, potentially allowing for one thread-bound Session per factory.
SessionFactory.getCurrentSession()
is required for Hibernate access code that needs to support this transaction handling mechanism, with the SessionFactory being configured with SpringSessionContext.
Supports custom isolation levels, and timeouts that get applied as Hibernate transaction timeouts.
This transaction manager is appropriate for applications that use a single Hibernate SessionFactory for transactional data access, but it also supports direct DataSource access within a transaction (i.e. plain JDBC code working with the same DataSource). This allows for mixing services which access Hibernate and services which use plain JDBC (without being aware of Hibernate)! Application code needs to stick to the same simple Connection lookup pattern as with org.springframework.jdbc.datasource.DataSourceTransactionManager (i.e.
org.springframework.jdbc.datasource.DataSourceUtils#getConnection
or going through a org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy).
Note: To be able to register a DataSource's Connection for plain JDBC code, this instance needs to be aware of the DataSource (
#setDataSource
). The given DataSource should obviously match the one used by the given SessionFactory.
JTA (usually through org.springframework.transaction.jta.JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. The DataSource that Hibernate uses needs to be JTA-enabled in such a scenario (see container setup).
This transaction manager supports nested transactions via JDBC 3.0 Savepoints. The
#setNestedTransactionAllowed
"nestedTransactionAllowed"} flag defaults to "false", though, as nested transactions will just apply to the JDBC Connection, not to the Hibernate Session and its cached entity objects and related context. You can manually set the flag to "true" if you want to use nested transactions for JDBC access code which participates in Hibernate transactions (provided that your JDBC driver supports Savepoints).
Note that Hibernate itself does not support nested transactions! Hence, do not expect Hibernate access code to semantically participate in a nested transaction.
javax.servlet.Filter that converts posted method parameters into HTTP methods, retrievable via
HttpServletRequest#getMethod()
. Since browsers currently only support GET and POST, a common technique - used by the Prototype library, for instance - is to use a normal POST with an additional hidden form field (
_method
) to pass the "real" HTTP method along. This filter reads that parameter and changes the
HttpServletRequestWrapper#getMethod()
return value accordingly.
The name of the request parameter defaults to
_method
, but can be adapted via the
methodParam
property.
NOTE: This filter needs to run after multipart processing in case of a multipart POST request, due to its inherent need for checking a POST body parameter.
So typically, put a Spring org.springframework.web.multipart.support.MultipartFilter
before
this HiddenHttpMethodFilter in your
web.xml
filter chain.
Reactive WebFilter that converts posted method parameters into HTTP methods, retrievable via
ServerHttpRequest#getMethod()
. Since browsers currently only support GET and POST, a common technique is to use a normal POST with an additional hidden form field (
_method
) to pass the "real" HTTP method along. This filter reads that parameter and changes the
ServerHttpRequest#getMethod()
return value using
ServerWebExchange#mutate()
.
The name of the request parameter defaults to
_method
, but can be adapted via the
methodParamName
property.
The
<hidden>
tag renders an HTML 'input' tag with type 'hidden' using the bound value.
Example (binding to 'name' property of form backing object):
<form:hidden path="name"/>
Attribute Summary Attribute Required? Runtime Expression? Description
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
Path to property for data binding
org.springframework.test.web.servlet.htmlunit.HostRequestMatcher
A WebRequestMatcher that allows matching on the host and optionally the port of
WebRequest#getUrl()
.
For example, the following would match any request to the host
"code.jquery.com"
without regard for the port.
WebRequestMatcher cdnMatcher = new HostMatcher("code.jquery.com");
Multiple hosts can also be passed in. For example, the following would match any request to the host
"code.jquery.com"
or the host
"cdn.com"
without regard for the port.
WebRequestMatcher cdnMatcher = new HostMatcher("code.jquery.com", "cdn.com");
Alternatively, one can also specify the port. For example, the following would match any request to the host
"code.jquery.com"
with the port of
80
.
WebRequestMatcher cdnMatcher = new HostMatcher("code.jquery.com:80");
The above
cdnMatcher
would match
"http://code.jquery.com/jquery.js"
which has a default port of
80
and
"http://code.jquery.com:80/jquery.js"
. However, it would not match
"https://code.jquery.com/jquery.js"
which has a default port of
443
.
org.springframework.aop.TargetSource implementation that caches a local target object, but allows the target to be swapped while the application is running.
If configuring an object of this class in a Spring IoC container, use constructor injection.
This TargetSource is serializable if the target is at the time of serialization.
org.springframework.jdbc.support.incrementer.HsqlMaxValueIncrementerDataFieldMaxValueIncrementer that increments the maximum value of a given HSQL table with the equivalent of an auto-increment column. Note: If you use this class, your HSQL key column should NOT be auto-increment, as the sequence table does the job.
The sequence is kept in a table. There should be one sequence table per table that needs an auto-generated key.
Example:
create table tab (id int not null primary key, text varchar(100)); create table tab_sequence (value identity); insert into tab_sequence values(0);
If "cacheSize" is set, the intermediate values are served without querying the database. If the server or your application is stopped or crashes or a transaction is rolled back, the unused values will never be served. The maximum hole size in numbering is consequently the value of cacheSize.
NOTE: HSQL now supports sequences and you should consider using them instead: HsqlSequenceMaxValueIncrementer
org.springframework.jdbc.support.incrementer.HsqlSequenceMaxValueIncrementerDataFieldMaxValueIncrementer that retrieves the next value of a given HSQL sequence. Thanks to Guillaume Bilodeau for the suggestion!
NOTE: This is an alternative to using a regular table to support generating unique keys that was necessary in previous versions of HSQL.
org.springframework.web.servlet.tags.HtmlEscapeTag
The
<htmlEscape>
tag sets default HTML escape value for the current page. The actual value can be overridden by escaping-aware tags. The default is "false".
Note: You can also set a "defaultHtmlEscape" web.xml context-param. A page-level setting overrides a context-param.
Attribute Summary Attribute Required? Runtime Expression? Description defaultHtmlEscape true true Set the default value for HTML escaping, to be put into the current PageContext. org.springframework.web.util.HtmlUtilsUtility class for HTML escaping. Escapes and unescapes based on the W3C HTML 4.01 recommendation, handling character entity references.
Reference: http://www.w3.org/TR/html4/charset.html
For a comprehensive set of String escaping utilities, consider Apache Commons Lang and its StringEscapeUtils class. We are not using that class here to avoid a runtime dependency on Commons Lang just for HTML escaping. Furthermore, Spring's HTML escaping is more flexible and 100% HTML 4.0 compliant.
org.springframework.remoting.httpinvoker.HttpComponentsHttpInvokerRequestExecutororg.springframework.remoting.httpinvoker.HttpInvokerRequestExecutor implementation that uses Apache HttpComponents HttpClient to execute POST requests.
Allows to use a pre-configured org.apache.http.client.HttpClient instance, potentially with authentication, HTTP connection pooling, etc. Also designed for easy subclassing, providing specific template methods.
As of Spring 4.1, this request executor requires Apache HttpComponents 4.3 or higher.
org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessorResolves HttpEntity and RequestEntity method argument values and also handles HttpEntity and ResponseEntity return values.
An HttpEntity return type has a specific purpose. Therefore this handler should be configured ahead of handlers that support any return value type annotated with
@ModelAttribute
or
@ResponseBody
to ensure they don't take over.
Connector that handles requests by invoking an HttpHandler rather than making actual requests to a network socket.
Internally the connector uses and adapts MockClientHttpRequest and MockClientHttpResponse to MockServerHttpRequest and MockServerHttpResponse.
org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBeanFactoryBean for HTTP invoker proxies. Exposes the proxied service for use as a bean reference, using the specified service interface.
The service URL must be an HTTP URL exposing an HTTP invoker service. Optionally, a codebase URL can be specified for on-demand dynamic code download from a remote location. For details, see HttpInvokerClientInterceptor docs.
Serializes remote invocation objects and deserializes remote invocation result objects. Uses Java serialization just like RMI, but provides the same ease of setup as Caucho's HTTP-based Hessian protocol.
HTTP invoker is the recommended protocol for Java-to-Java remoting. It is more powerful and more extensible than Hessian, at the expense of being tied to Java. Nevertheless, it is as easy to set up as Hessian, which is its main advantage compared to RMI.
WARNING: Be aware of vulnerabilities due to unsafe Java deserialization: Manipulated input streams could lead to unwanted code execution on the server during the deserialization step. As a consequence, do not expose HTTP invoker endpoints to untrusted clients but rather just between your own services. In general, we strongly recommend any other message format (e.g. JSON) instead.
org.springframework.remoting.httpinvoker.HttpInvokerRequestExecutorStrategy interface for actual execution of an HTTP invoker request. Used by HttpInvokerClientInterceptor and its subclass HttpInvokerProxyFactoryBean.
Two implementations are provided out of the box:
SimpleHttpInvokerRequestExecutor
:
Uses JDK facilities to execute POST requests, without support for HTTP authentication or advanced configuration options.
HttpComponentsHttpInvokerRequestExecutor
:
Uses Apache's Commons HttpClient to execute POST requests, allowing to use a preconfigured HttpClient instance (potentially with authentication, HTTP connection pooling, etc).
javax.servlet.Filter that makes form encoded data available through the
ServletRequest.getParameter*()
family of methods during HTTP PUT or PATCH requests.
The Servlet spec requires form data to be available for HTTP POST but not for HTTP PUT or PATCH requests. This filter intercepts HTTP PUT and PATCH requests where content type is
'application/x-www-form-urlencoded'
, reads form encoded content from the body of the request, and wraps the ServletRequest in order to make the form data available as request parameters just like it is for HTTP POST requests.
Simple HttpServlet that delegates to an HttpRequestHandler bean defined in Spring's root web application context. The target bean name must match the HttpRequestHandlerServlet servlet-name as defined in
web.xml
.
This can for example be used to expose a single Spring remote exporter, such as org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter or org.springframework.remoting.caucho.HessianServiceExporter, per HttpRequestHandlerServlet definition. This is a minimal alternative to defining remote exporters as beans in a DispatcherServlet context (with advanced mapping and interception facilities being available there).
org.springframework.http.client.support.HttpRequestWrapperProvides a convenient implementation of the HttpRequest interface that can be overridden to adapt the request.
These methods default to calling through to the wrapped request object.
org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor
An interceptor to copy information from the HTTP session to the "handshake attributes" map to made available via
WebSocketSession#getAttributes()
.
Copies a subset or all HTTP session attributes and/or the HTTP session id under the key
#HTTP_SESSION_ID_ATTR_NAME
.
Servlet HttpSessionListener that automatically exposes the session mutex when an HttpSession gets created. To be registered as a listener in
web.xml
.
The session mutex is guaranteed to be the same object during the entire lifetime of the session, available under the key defined by the
SESSION_MUTEX_ATTRIBUTE
constant. It serves as a safe reference to synchronize on for locking on the current session.
In many cases, the HttpSession reference itself is a safe mutex as well, since it will always be the same object reference for the same active logical session. However, this is not guaranteed across different servlet containers; the only 100% safe way is a session mutex.
org.springframework.web.server.adapter.HttpWebHandlerAdapterDefault adapter of WebHandler to the HttpHandler contract.
By default creates and configures a DefaultServerWebExchange and then invokes the target
WebHandler
.
An implementation of the
ObjectNamingStrategy
interface that creates a name based on the identity of a given instance.
The resulting
ObjectName
will be in the form
package
:class=
class name
,hashCode=
identity hash (in hex)
Test annotation to indicate whether a test is enabled or disabled for a specific testing profile.
In the context of this annotation, the term
profile
refers to a Java system property by default; however, the semantics can be changed by implementing a custom ProfileValueSource. If the configured
ProfileValueSource
returns a matching
#value
for the declared
#name
, the test will be enabled. Otherwise, the test will be disabled and effectively
ignored
.
@IfProfileValue
can be applied at the class level, the method level, or both. Class-level usage of
@IfProfileValue
takes precedence over method-level usage for any methods within that class or its subclasses. Specifically, a test is enabled if it is enabled both at the class level
and
at the method level; the absence of
@IfProfileValue
means the test is implicitly enabled. This is analogous to the semantics of JUnit's org.junit.Ignore annotation, except that the presence of
@Ignore
always disables a test.
ProfileValueSource
implementation (which is configured by default), you can configure a test method to run only on Java VMs from Oracle as follows:
@IfProfileValue(name = "java.vendor", value = "Oracle Corporation") public void testSomething() { // ... }
'OR' Semantics
You can alternatively configure
@IfProfileValue
with
OR
semantics for multiple
#values
. The following test will be enabled if a
ProfileValueSource
has been appropriately configured for the
"test-groups"
profile with a value of either
unit-tests
or
integration-tests
. This functionality is similar to TestNG's support for test
groups
and JUnit's experimental support for test
categories
.
@IfProfileValue(name = "test-groups", values = { "unit-tests", "integration-tests" }) public void testWhichRunsForUnitOrIntegrationTestGroups() { // ... }
@IfProfileValue
vs.
@Profile
Although the
@IfProfileValue
and org.springframework.context.annotation.Profile annotations both involve
profiles
, they are not directly related.
@Profile
involves bean definition profiles configured in the org.springframework.core.env.Environment; whereas,
@IfProfileValue
is used to enable or disable tests.
As of Spring Framework 4.0, this annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.messaging.support.ImmutableMessageChannelInterceptor
A simpler interceptor that calls
MessageHeaderAccessor#setImmutable()
on the headers of messages passed through the preSend method.
When configured as the last interceptor in a chain, it allows the component sending the message to leave headers mutable for interceptors to modify prior to the message actually being sent and exposed to concurrent access.
org.springframework.context.annotation.ImportResourceIndicates one or more resources containing bean definitions to import.
Like Import, this annotation provides functionality similar to the
<import/>
element in Spring XML. It is typically used when designing Configuration classes to be bootstrapped by an AnnotationConfigApplicationContext, but where some XML functionality such as namespaces is still necessary.
By default, arguments to the
#value
attribute will be processed using a org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader if ending in
".groovy"
; otherwise, an org.springframework.beans.factory.xml.XmlBeanDefinitionReader will be used to parse Spring
<beans/>
XML files. Optionally, the
#reader
attribute may be declared, allowing the user to choose a custom BeanDefinitionReader implementation.
Indicate that the annotated element represents a stereotype for the index.
The
CandidateComponentsIndex
is an alternative to classpath scanning that uses a metadata file generated at compilation time. The index allows retrieving the candidate components (i.e. fully qualified name) based on a stereotype. This annotation instructs the generator to index the element on which the annotated element is present or if it implements or extends from the annotated element. The stereotype is the fully qualified name of the annotated element.
Consider the default Component annotation that is meta-annotated with this annotation. If a component is annotated with Component, an entry for that component will be added to the index using the
org.springframework.stereotype.Component
stereotype.
This annotation is also honored on meta-annotations. Consider this custom annotation:
package com.example; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Indexed @Service public @interface PrivilegedService { ... }
If the above annotation is present on a type, it will be indexed with two stereotypes:
org.springframework.stereotype.Component
and
com.example.PrivilegedService
. While Service isn't directly annotated with
Indexed
, it is meta-annotated with Component.
It is also possible to index all implementations of a certain interface or all the subclasses of a given class by adding
@Indexed
on it. Consider this base interface:
package com.example; @Indexed public interface AdminService { ... }
Now, consider an implementation of this
AdminService
somewhere:
package com.example.foo; import com.example.AdminService; public class ConfigurationAdminService implements AdminService { ... }
Because this class implements an interface that is indexed, it will be automatically included with the
com.example.AdminService
stereotype. If there are more
@Indexed
interfaces and/or superclasses in the hierarchy, the class will map to all their stereotypes.
org.springframework.core.InfrastructureProxy
Interface to be implemented by transparent resource proxies that need to be considered as equal to the underlying resource, for example for consistent lookup key comparisons. Note that this interface does imply such special semantics and does not constitute a general-purpose mixin!
Such wrappers will automatically be unwrapped for key comparisons in org.springframework.transaction.support.TransactionSynchronizationManager.
Only fully transparent proxies, e.g. for redirection or service lookups, are supposed to implement this interface. Proxies that decorate the target object with new behavior, such as AOP proxies, do not qualify here!
org.springframework.web.bind.annotation.InitBinderAnnotation that identifies methods which initialize the org.springframework.web.bind.WebDataBinder which will be used for populating command and form object arguments of annotated handler methods.
Such init-binder methods support all arguments that RequestMapping supports, except for command/form objects and corresponding validation result objects. Init-binder methods must not have a return value; they are usually declared as
void
.
Typical arguments are org.springframework.web.bind.WebDataBinder in combination with org.springframework.web.context.request.WebRequest or java.util.Locale, allowing to register context-specific editors.
org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessororg.springframework.beans.factory.config.BeanPostProcessor implementation that invokes annotated init and destroy methods. Allows for an annotation alternative to Spring's org.springframework.beans.factory.InitializingBean and org.springframework.beans.factory.DisposableBean callback interfaces.
The actual annotation types that this post-processor checks for can be configured through the
"initAnnotationType"
and
"destroyAnnotationType"
properties. Any custom annotation can be used, since there are no required annotation attributes.
Init and destroy annotations may be applied to methods of any visibility: public, package-protected, protected, or private. Multiple such methods may be annotated, but it is recommended to only annotate one single init method and destroy method, respectively.
Spring's org.springframework.context.annotation.CommonAnnotationBeanPostProcessor supports the JSR-250 javax.annotation.PostConstruct and javax.annotation.PreDestroy annotations out of the box, as init annotation and destroy annotation, respectively. Furthermore, it also supports the javax.annotation.Resource annotation for annotation-driven injection of named beans.
org.springframework.beans.propertyeditors.InputSourceEditor
Editor for
org.xml.sax.InputSource
, converting from a Spring resource location String to a SAX InputSource object.
Supports Spring-style URL notation: any fully qualified standard URL ("file:", "http:", etc) and Spring's special "classpath:" pseudo-URL.
org.springframework.beans.propertyeditors.InputStreamEditor
One-way PropertyEditor which can convert from a text String to a
java.io.InputStream
, interpreting the given String as a Spring resource location (e.g. a URL String).
Supports Spring-style URL notation: any fully qualified standard URL ("file:", "http:", etc.) and Spring's special "classpath:" pseudo-URL.
Note that such streams usually do not get closed by Spring itself!
org.springframework.core.io.InputStreamResourceResource implementation for a given InputStream.
Should only be used if no other specific
Resource
implementation is applicable. In particular, prefer ByteArrayResource or any of the file-based
Resource
implementations where possible.
In contrast to other
Resource
implementations, this is a descriptor for an
already opened
resource - therefore returning
true
from
#isOpen()
. Do not use an
InputStreamResource
if you need to keep the resource descriptor somewhere, or if you need to read from a stream multiple times.
The
<input>
tag renders an HTML 'input' tag with type 'text' using the bound value.
Attribute Summary Attribute Required? Runtime Expression? Description
accesskey
false
HTML Standard Attribute
false
HTML Optional Attribute
autocomplete
false
Common Optional Attribute
cssClass
false
HTML Optional Attribute
cssErrorClass
false
HTML Optional Attribute. Used when the bound field has errors.
cssStyle
false
HTML Optional Attribute
false
HTML Standard Attribute
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
false
HTML Standard Attribute
maxlength
false
HTML Optional Attribute
onblur
false
HTML Event Attribute
onchange
false
HTML Event Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onfocus
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
onselect
false
HTML Event Attribute
Path to property for data binding
readonly
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will make the HTML element readonly.
false
HTML Optional Attribute
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
org.springframework.format.datetime.standard.InstantFormatter
Formatter implementation for a JSR-310 java.time.Instant, following JSR-310's parsing rules for an Instant (that is, not using a configurable java.time.format.DateTimeFormatter): accepting the default
ISO_INSTANT
format as well as
RFC_1123_DATE_TIME
(which is commonly used for HTTP date header values), as of Spring 4.3.
Adapter that implements all methods on SmartInstantiationAwareBeanPostProcessor as no-ops, which will not change normal processing of each bean instantiated by the container. Subclasses may override merely those methods that they are actually interested in.
Note that this base class is only recommendable if you actually require InstantiationAwareBeanPostProcessor functionality. If all you need is plain BeanPostProcessor functionality, prefer a straight implementation of that (simpler) interface.
org.springframework.beans.factory.support.InstantiationStrategyInterface responsible for creating instances corresponding to a root bean definition.
This is pulled out into a strategy as various approaches are possible, including using CGLIB to create subclasses on the fly to support Method Injection.
org.springframework.instrument.classloading.InstrumentationLoadTimeWeaverLoadTimeWeaver relying on VM Instrumentation.
Start the JVM specifying the Java agent to be used, like as follows:
-javaagent:path/to/org.springframework.instrument.jar
where
org.springframework.instrument.jar
is a JAR file containing the InstrumentationSavingAgent class, as shipped with Spring.
In Eclipse, for example, set the "Run configuration"'s JVM args to be of the form:
-javaagent:${project_loc}/lib/org.springframework.instrument.jar
Generic callback interface for code that operates on a CCI Interaction. Allows to execute any number of operations on a single Interaction, for example a single execute call or repeated execute calls with varying parameters.
This is particularly useful for delegating to existing data access code that expects an Interaction to work on and throws ResourceException. For newly written code, it is strongly recommended to use CciTemplate's more specific
execute
variants.
Subclass of
AbstractReflectiveMBeanInfoAssembler
that allows for the management interface of a bean to be defined using arbitrary interfaces. Any methods or properties that are defined in those interfaces are exposed as MBean operations and attributes.
By default, this class votes on the inclusion of each operation or attribute based on the interfaces implemented by the bean class. However, you can supply an array of interfaces via the
managedInterfaces
property that will be used instead. If you have multiple beans and you wish each bean to use a different set of interfaces, then you can map bean keys (that is the name used to pass the bean to the
MBeanExporter
) to a list of interface names using the
interfaceMappings
property.
If you specify values for both
interfaceMappings
and
managedInterfaces
, Spring will attempt to find interfaces in the mappings first. If no interfaces for the bean are found, it will use the interfaces defined by
managedInterfaces
.
Wrapper for a JSP or other resource within the same web application. Exposes model objects as request attributes and forwards the request to the specified resource URL using a javax.servlet.RequestDispatcher.
A URL for this view is supposed to specify a resource within the web application, suitable for RequestDispatcher's
forward
or
include
method.
If operating within an already included request or within a response that has already been committed, this view will fall back to an include instead of a forward. This can be enforced by calling
response.flushBuffer()
(which will commit the response) before rendering the view.
Typical usage with InternalResourceViewResolver looks as follows, from the perspective of the DispatcherServlet context definition:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
Every view name returned from a handler will be translated to a JSP resource (for example: "myView" -> "/WEB-INF/jsp/myView.jsp"), using this view class by default.
org.springframework.mail.javamail.InternetAddressEditor
Editor for
java.mail.internet.InternetAddress
, to directly populate an InternetAddress property.
Expects the same syntax as InternetAddress's constructor with a String argument. Converts empty Strings into null values.
org.springframework.web.util.IntrospectorCleanupListener
Listener that flushes the JDK's java.beans.Introspector cache on web app shutdown. Register this listener in your
web.xml
to guarantee proper release of the web application class loader and its loaded classes.
If the JavaBeans Introspector has been used to analyze application classes, the system-level Introspector cache will hold a hard reference to those classes. Consequently, those classes and the web application class loader will not be garbage-collected on web app shutdown! This listener performs proper cleanup, to allow for garbage collection to take effect.
Unfortunately, the only way to clean up the Introspector is to flush the entire cache, as there is no way to specifically determine the application's classes referenced there. This will remove cached introspection results for all other applications in the server too.
Note that this listener is not necessary when using Spring's beans infrastructure within the application, as Spring's own introspection results cache will immediately flush an analyzed class from the JavaBeans Introspector cache and only hold a cache within the application's own ClassLoader. Although Spring itself does not create JDK Introspector leaks, note that this listener should nevertheless be used in scenarios where the Spring framework classes themselves reside in a 'common' ClassLoader (such as the system ClassLoader). In such a scenario, this listener will properly clean up Spring's introspection cache.
Application classes hardly ever need to use the JavaBeans Introspector directly, so are normally not the cause of Introspector resource leaks. Rather, many libraries and frameworks do not clean up the Introspector: e.g. Struts and Quartz.
Note that a single such Introspector leak will cause the entire web app class loader to not get garbage collected! This has the consequence that you will see all the application's static class resources (like singletons) around after web app shutdown, which is not the fault of those classes!
This listener should be registered as the first one in
web.xml
, before any application listeners such as Spring's ContextLoaderListener.
This allows the listener to take full effect at the right time of the lifecycle.
Exception thrown when a ResultSet has been accessed in an invalid fashion. Such exceptions always have a
java.sql.SQLException
root cause.
This typically happens when an invalid ResultSet column index or name has been specified. Also thrown by disconnected SqlRowSets.
org.springframework.jca.cci.InvalidResultSetAccessException
Exception thrown when a ResultSet has been accessed in an invalid fashion. Such exceptions always have a
java.sql.SQLException
root cause.
This typically happens when an invalid ResultSet column index or name has been specified.
org.springframework.web.method.support.InvocableHandlerMethodProvides a method for invoking the handler method for a given request after resolving its method argument values through registered HandlerMethodArgumentResolvers.
Argument resolution often requires a WebDataBinder for data binding or for type conversion. Use the
#setDataBinderFactory(WebDataBinderFactory)
property to supply a binder factory to pass to argument resolvers.
Use
#setHandlerMethodArgumentResolvers
to customize the list of argument resolvers.
This interface represents an invocation in the program.
An invocation is a joinpoint and can be intercepted by an interceptor.
org.springframework.jdbc.datasource.IsolationLevelDataSourceAdapter
An adapter for a target javax.sql.DataSource, applying the current Spring transaction's isolation level (and potentially specified user credentials) to every
getConnection
call. Also applies the read-only flag, if specified.
Can be used to proxy a target JNDI DataSource that does not have the desired isolation level (and user credentials) configured. Client code can work with this DataSource as usual, not worrying about such settings.
Inherits the capability to apply specific user credentials from its superclass UserCredentialsDataSourceAdapter; see the latter's javadoc for details on that functionality (e.g.
#setCredentialsForCurrentThread
).
WARNING:
This adapter simply calls
java.sql.Connection#setTransactionIsolation
and/or
java.sql.Connection#setReadOnly
for every Connection obtained from it. It does, however,
not
reset those settings; it rather expects the target DataSource to perform such resetting as part of its connection pool handling.
Make sure that the target DataSource properly cleans up such transaction state.
DataSource that routes to one of various target DataSources based on the current transaction isolation level. The target DataSources need to be configured with the isolation level name as key, as defined on the org.springframework.transaction.TransactionDefinition.
This is particularly useful in combination with JTA transaction management (typically through Spring's org.springframework.transaction.jta.JtaTransactionManager). Standard JTA does not support transaction-specific isolation levels. Some JTA providers support isolation levels as a vendor-specific extension (e.g. WebLogic), which is the preferred way of addressing this. As alternative (e.g. on WebSphere), the target database can be represented through multiple JNDI DataSources, each configured with a different isolation level (for the entire DataSource). The present DataSource router allows to transparently switch to the appropriate DataSource based on the current transaction's isolation level.
The configuration can for example look like this, assuming that the target DataSources are defined as individual Spring beans with names "myRepeatableReadDataSource", "mySerializableDataSource" and "myDefaultDataSource":
<bean id="dataSourceRouter" class="org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter"> <property name="targetDataSources"> <map> <entry key="ISOLATION_REPEATABLE_READ" value-ref="myRepeatableReadDataSource"/> <entry key="ISOLATION_SERIALIZABLE" value-ref="mySerializableDataSource"/> </map> </property> <property name="defaultTargetDataSource" ref="myDefaultDataSource"/> </bean>
Alternatively, the keyed values can also be data source names, to be resolved through a
DataSourceLookup
: by default, JNDI names for a standard JNDI lookup. This allows for a single concise definition without the need for separate DataSource bean definitions.
<bean id="dataSourceRouter" class="org.springframework.jdbc.datasource.lookup.IsolationLevelDataSourceRouter"> <property name="targetDataSources"> <map> <entry key="ISOLATION_REPEATABLE_READ" value="java:comp/env/jdbc/myrrds"/> <entry key="ISOLATION_SERIALIZABLE" value="java:comp/env/jdbc/myserds"/> </map> </property> <property name="defaultTargetDataSource" value="java:comp/env/jdbc/mydefds"/> </bean>
Note: If you are using this router in combination with Spring's org.springframework.transaction.jta.JtaTransactionManager, don't forget to switch the "allowCustomIsolationLevels" flag to "true". (By default, JtaTransactionManager will only accept a default isolation level because of the lack of isolation level support in standard JTA itself.)
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="allowCustomIsolationLevels" value="true"/> </bean>
org.springframework.instrument.classloading.jboss.JBossLoadTimeWeaver
LoadTimeWeaver implementation for JBoss's instrumentable ClassLoader. Thanks to Ales Justin and Marius Bogoevici for the initial prototype.
As of Spring Framework 5.0, this weaver supports WildFly 8+.
org.springframework.cache.jcache.interceptor.JCacheAspectSupportBase class for JSR-107 caching aspects, such as the JCacheInterceptor or an AspectJ aspect.
Use the Spring caching abstraction for cache-related operations. No JSR-107 javax.cache.Cache or javax.cache.CacheManager are required to process standard JSR-107 cache annotations.
The JCacheOperationSource is used for determining caching operations
A cache aspect is serializable if its
JCacheOperationSource
is serializable.
org.springframework.cache.Cache implementation on top of a javax.cache.Cache instance.
Note: This class has been updated for JCache 1.0, as of Spring 4.0.
org.springframework.cache.jcache.JCacheCacheManagerorg.springframework.cache.CacheManager implementation backed by a JCache javax.cache.CacheManager.
Note: This class has been updated for JCache 1.0, as of Spring 4.0.
org.springframework.cache.jcache.config.JCacheConfigurerExtension of CachingConfigurer for the JSR-107 implementation.
To be implemented by classes annotated with org.springframework.cache.annotation.EnableCaching that wish or need to specify explicitly how exception caches are resolved for annotation-driven cache management. Consider extending JCacheConfigurerSupport, which provides a stub implementation of all interface methods.
See org.springframework.cache.annotation.EnableCaching for general examples and context; see
#exceptionCacheResolver()
for detailed instructions.
An extension of CachingConfigurerSupport that also implements JCacheConfigurer.
Users of JSR-107 annotations may extend from this class rather than implementing from JCacheConfigurer directly.
org.springframework.cache.jcache.JCacheManagerFactoryBeanFactoryBean for a JCache javax.cache.CacheManager, obtaining a pre-defined CacheManager by name through the standard JCache javax.cache.Caching class.
Note: This class has been updated for JCache 1.0, as of Spring 4.0.
org.springframework.core.env.JOptCommandLinePropertySource
CommandLinePropertySource implementation backed by a JOpt OptionSet. Typical usage Configure and execute an
OptionParser
against the
String[]
of arguments supplied to the
main
method, and create a JOptCommandLinePropertySource using the resulting
OptionSet
object:
public static void main(String[] args) { OptionParser parser = new OptionParser(); parser.accepts("option1"); parser.accepts("option2").withRequiredArg(); OptionSet options = parser.parse(args); PropertySource ps = new JOptCommandLinePropertySource(options); // ... }
See CommandLinePropertySource for complete general usage examples.
Requires JOpt Simple version 4.3 or higher. Tested against JOpt up until 5.0.
org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean
A FactoryBean for creating a Jackson 2.x ObjectMapper (default) or XmlMapper (
createXmlMapper
property set to true) with setters to enable or disable Jackson features from within XML configuration.
It customizes Jackson defaults properties with the following ones:
MapperFeature#DEFAULT_VIEW_INCLUSION
is disabled
DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES
is disabled
Example usage with MappingJackson2HttpMessageConverter:
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" p:autoDetectFields="false" p:autoDetectGettersSetters="false" p:annotationIntrospector-ref="jaxbAnnotationIntrospector" /> </property> </bean>
Example usage with MappingJackson2JsonView:
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" p:failOnEmptyBeans="false" p:indentOutput="true"> <property name="serializers"> <array> <bean class="org.mycompany.MyCustomSerializer" /> </array> </property> </bean> </property> </bean>
In case there are no specific setters provided (for some rarely used options), you can still use the more general methods
#setFeaturesToEnable
and
#setFeaturesToDisable
.
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="featuresToEnable"> <array> <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRAP_ROOT_VALUE"/> <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.CLOSE_CLOSEABLE"/> </array> </property> <property name="featuresToDisable"> <array> <util:constant static-field="com.fasterxml.jackson.databind.MapperFeature.USE_ANNOTATIONS"/> </array> </property> </bean>
It also automatically registers the following well-known modules if they are detected on the classpath:
In case you want to configure Jackson's ObjectMapper with a custom Module, you can register one or more such Modules by class name via
#setModulesToInstall
:
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="modulesToInstall" value="myapp.jackson.MySampleModule,myapp.jackson.MyOtherModule"/> </bean
Compatible with Jackson 2.6 and higher, as of Spring 4.3.
org.springframework.aop.interceptor.JamonPerformanceMonitorInterceptorPerformance monitor interceptor that uses JAMon library to perform the performance measurement on the intercepted method and output the stats. In addition, it tracks/counts exceptions thrown by the intercepted method. The stack traces can be viewed in the JAMon web application.
This code is inspired by Thierry Templier's blog.
org.springframework.mail.javamail.JavaMailSenderImplProduction implementation of the JavaMailSender interface, supporting both JavaMail MimeMessage and Spring SimpleMailMessage. Can also be used as a plain org.springframework.mail.MailSender implementation.
Allows for defining all settings locally as bean properties. Alternatively, a pre-configured JavaMail javax.mail.Session can be specified, possibly pulled from an application server's JNDI environment.
Non-default properties in this object will always override the settings in the JavaMail
Session
. Note that if overriding all values locally, there is no added value in setting a pre-configured
Session
.
Utility class for JavaScript escaping. Escapes based on the JavaScript 1.5 recommendation.
Reference: JavaScript Guide on Mozilla Developer Network.
org.springframework.http.converter.xml.Jaxb2CollectionHttpMessageConverter
An
HttpMessageConverter
that can read XML collections using JAXB2.
This converter can read Collection that contain classes annotated with XmlRootElement and XmlType. Note that this converter does not support writing.
org.springframework.oxm.jaxb.Jaxb2Marshaller
Implementation of the
GenericMarshaller
interface for JAXB 2.2.
The typical usage will be to set either the "contextPath" or the "classesToBeBound" property on this bean, possibly customize the marshaller and unmarshaller by setting properties, schemas, adapters, and listeners, and to refer to it.
org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverterImplementation of org.springframework.http.converter.HttpMessageConverter that can read and write XML using JAXB2.
This converter can read classes annotated with XmlRootElement and XmlType, and write classes annotated with XmlRootElement, or subclasses thereof.
Note: When using Spring's Marshaller/Unmarshaller abstractions from
spring-oxm
, you should use the MarshallingHttpMessageConverter instead.
Base class for org.springframework.jdbc.core.JdbcTemplate and other JDBC-accessing DAO helpers, defining common properties such as DataSource and exception translator.
Not intended to be used directly. See org.springframework.jdbc.core.JdbcTemplate.
org.springframework.jdbc.core.support.JdbcBeanDefinitionReaderBean definition reader that reads values from a database table, based on a given SQL statement.
Expects columns for bean name, property name and value as String. Formats for each are identical to the properties format recognized by PropertiesBeanDefinitionReader.
NOTE: This is mainly intended as an example for a custom JDBC-based bean definition reader. It does not aim to offer comprehensive functionality.
org.springframework.jdbc.core.support.JdbcDaoSupportConvenient super class for JDBC-based data access objects.
Requires a javax.sql.DataSource to be set, providing a org.springframework.jdbc.core.JdbcTemplate based on it to subclasses through the
#getJdbcTemplate()
method.
This base class is mainly intended for JdbcTemplate usage but can also be used when working with a Connection directly or when using
org.springframework.jdbc.object
operation objects.
Convenient base class for JDBC-aware transaction objects. Can contain a ConnectionHolder with a JDBC
Connection
, and implements the SavepointManager interface based on that
ConnectionHolder
.
Allows for programmatic management of JDBC java.sql.Savepoint. Spring's org.springframework.transaction.support.DefaultTransactionStatus automatically delegates to this, as it autodetects transaction objects which implement the SavepointManager interface.
org.springframework.aop.support.JdkRegexpMethodPointcut
Regular expression pointcut based on the
java.util.regex
package. Supports the following JavaBean properties:
Note: the regular expressions must be a match. For example,
.*get.*
will match com.mycom.Foo.getBar().
get.*
will not.
A WebSocketClient implementation for use with Jetty org.eclipse.jetty.websocket.client.WebSocketClient.
Note:
the Jetty
WebSocketClient
requires lifecycle management and must be started and stopped. This is automatically managed when this class is declared as a Spring bean and created with the default constructor. See constructor notes for more details.
Initiates WebSocket requests to a WebSocket server programmatically through the Jetty WebSocket API.
As of 4.1 this class implements Lifecycle rather than org.springframework.context.SmartLifecycle. Use org.springframework.web.socket.client.WebSocketConnectionManager instead to auto-start a WebSocket connection.
org.springframework.web.socket.sockjs.client.JettyXhrTransportAn XHR transport based on Jetty's org.eclipse.jetty.client.HttpClient.
When used for testing purposes (e.g. load testing) the
HttpClient
properties must be set to allow a larger than usual number of connections and threads. For example:
HttpClient httpClient = new HttpClient(); httpClient.setMaxConnectionsPerDestination(1000); httpClient.setExecutor(new QueuedThreadPool(500));
org.springframework.oxm.jibx.JibxMarshaller
Implementation of the
Marshaller
and
Unmarshaller
interfaces for JiBX.
The typical usage will be to set the
targetClass
and optionally the
bindingName
property on this bean.
Convenient super class for application classes that need JMS access.
Requires a ConnectionFactory or a JmsTemplate instance to be set. It will create its own JmsTemplate if a ConnectionFactory is passed in. A custom JmsTemplate instance can be created for a given ConnectionFactory through overriding the
#createJmsTemplate
method.
org.aopalliance.intercept.MethodInterceptor for accessing a JMS-based remote service.
Serializes remote invocation objects and deserializes remote invocation result objects. Uses Java serialization just like RMI, but with the JMS provider as communication infrastructure.
To be configured with a javax.jms.QueueConnectionFactory and a target queue (either as javax.jms.Queue reference or as queue name).
Thanks to James Strachan for the original prototype that this JMS invoker mechanism was inspired by!
org.springframework.jms.remoting.JmsInvokerProxyFactoryBeanFactoryBean for JMS invoker proxies. Exposes the proxied service for use as a bean reference, using the specified service interface.
Serializes remote invocation objects and deserializes remote invocation result objects. Uses Java serialization just like RMI, but with the JMS provider as communication infrastructure.
To be configured with a javax.jms.QueueConnectionFactory and a target queue (either as javax.jms.Queue reference or as queue name).
org.springframework.jms.remoting.JmsInvokerServiceExporterJMS message listener that exports the specified service bean as a JMS service endpoint, accessible via a JMS invoker proxy.
Note that this class implements Spring's org.springframework.jms.listener.SessionAwareMessageListener interface, since it requires access to the active JMS Session. Hence, this class can only be used with message listener containers which support the SessionAwareMessageListener interface (e.g. Spring's org.springframework.jms.listener.DefaultMessageListenerContainer).
Thanks to James Strachan for the original prototype that this JMS invoker mechanism was inspired by!
org.springframework.jms.annotation.JmsListenerAnnotationBeanPostProcessorBean post-processor that registers methods annotated with JmsListener to be invoked by a JMS message listener container created under the cover by a org.springframework.jms.config.JmsListenerContainerFactory according to the attributes of the annotation.
Annotated methods can use flexible arguments as defined by JmsListener.
This post-processor is automatically registered by Spring's
<jms:annotation-driven>
XML element, and also by the EnableJms annotation.
Autodetects any JmsListenerConfigurer instances in the container, allowing for customization of the registry to be used, the default container factory or for fine-grained control over endpoints registration. See the EnableJms javadocs for complete usage details.
org.springframework.jms.annotation.JmsListenerConfigurerOptional interface to be implemented by a Spring managed bean willing to customize how JMS listener endpoints are configured. Typically used to define the default org.springframework.jms.config.JmsListenerContainerFactory to use or for registering JMS endpoints in a programmatic fashion as opposed to the declarative approach of using the @JmsListener annotation.
See @EnableJms for detailed usage examples.
org.springframework.jms.annotation.JmsListenersContainer annotation that aggregates several JmsListener annotations.
Can be used natively, declaring several nested JmsListener annotations. Can also be used in conjunction with Java 8's support for repeatable annotations, where JmsListener can simply be declared several times on the same method, implicitly generating this container annotation.
This annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.jms.listener.endpoint.JmsMessageEndpointFactoryJMS-specific implementation of the JCA 1.7 javax.resource.spi.endpoint.MessageEndpointFactory interface, providing transaction management capabilities for a JMS listener object (e.g. a javax.jms.MessageListener object).
Uses a static endpoint implementation, simply wrapping the specified message listener object and exposing all of its implemented interfaces on the endpoint instance.
Typically used with Spring's JmsMessageEndpointManager, but not tied to it. As a consequence, this endpoint factory could also be used with programmatic endpoint management on a native javax.resource.spi.ResourceAdapter instance.
org.springframework.jms.connection.JmsResourceHolderJMS resource holder, wrapping a JMS Connection and a JMS Session. JmsTransactionManager binds instances of this class to the thread, for a given JMS ConnectionFactory.
Note: This is an SPI class, not intended to be used by applications.
org.springframework.jms.listener.adapter.JmsResponseReturn type of any JMS listener method used to indicate the actual response destination alongside the response itself. Typically used when said destination needs to be computed at runtime.
The example below sends a response with the content of the
result
argument to the
queueOut Queue
:
package com.acme.foo; public class MyService { @JmsListener public JmsResponse process(String msg) { // process incoming message return JmsResponse.forQueue(result, "queueOut"); } }
If the destination does not need to be computed at runtime, org.springframework.messaging.handler.annotation.SendTo is the recommended declarative approach.
org.springframework.jms.connection.JmsTransactionManager
org.springframework.transaction.PlatformTransactionManager implementation for a single JMS javax.jms.ConnectionFactory. Binds a JMS Connection/Session pair from the specified ConnectionFactory to the thread, potentially allowing for one thread-bound Session per ConnectionFactory.
This local strategy is an alternative to executing JMS operations within JTA transactions. Its advantage is that it is able to work in any environment, for example a standalone application or a test suite, with any message broker as target. However, this strategy is not able to provide XA transactions, for example in order to share transactions between messaging and database access. A full JTA/XA setup is required for XA transactions, typically using Spring's org.springframework.transaction.jta.JtaTransactionManager as strategy.
Application code is required to retrieve the transactional JMS Session via
ConnectionFactoryUtils#getTransactionalSession
instead of a standard Java EE-style
ConnectionFactory#createConnection()
call with subsequent Session creation. Spring's org.springframework.jms.core.JmsTemplate will autodetect a thread-bound Session and automatically participate in it.
Alternatively, you can allow application code to work with the standard Java EE-style lookup pattern on a ConnectionFactory, for example for legacy code that is not aware of Spring at all. In that case, define a TransactionAwareConnectionFactoryProxy for your target ConnectionFactory, which will automatically participate in Spring-managed transactions.
The use of CachingConnectionFactory as a target for this transaction manager is strongly recommended. CachingConnectionFactory uses a single JMS Connection for all JMS access in order to avoid the overhead of repeated Connection creation, as well as maintaining a cache of Sessions. Each transaction will then share the same JMS Connection, while still using its own individual JMS Session.
The use of a
raw
target ConnectionFactory would not only be inefficient because of the lack of resource reuse. It might also lead to strange effects when your JMS driver doesn't accept
MessageProducer.close()
calls and/or
MessageConsumer.close()
calls before
Session.commit()
, with the latter supposed to commit all the messages that have been sent through the producer handle and received through the consumer handle. As a safe general solution, always pass in a CachingConnectionFactory into this transaction manager's
"connectionFactory"
property.
Transaction synchronization is turned off by default, as this manager might be used alongside a datastore-based Spring transaction manager such as the JDBC org.springframework.jdbc.datasource.DataSourceTransactionManager, which has stronger needs for synchronization.
org.springframework.jndi.JndiCallbackCallback interface to be implemented by classes that need to perform an operation (such as a lookup) in a JNDI context. This callback approach is valuable in simplifying error handling, which is performed by the JndiTemplate class. This is a similar to JdbcTemplate's approach.
Note that there is hardly any need to implement this callback interface, as JndiTemplate provides all usual JNDI operations via convenience methods.
org.springframework.jdbc.datasource.lookup.JndiDataSourceLookupJNDI-based DataSourceLookup implementation.
For specific JNDI configuration, it is recommended to configure the "jndiEnvironment"/"jndiTemplate" properties.
org.springframework.jms.support.destination.JndiDestinationResolverDestinationResolver implementation which interprets destination names as JNDI locations (with a configurable fallback strategy).
Allows for customizing the JNDI environment if necessary, for example specifying appropriate JNDI environment properties.
Dynamic queues and topics get cached by destination name. As a consequence, you need to use unique destination names across both queues and topics. Caching can be turned off through the
"cache"
flag.
Note that the fallback to resolution of dynamic destinations is turned
off
by default. Switch the
"fallbackToDynamicDestination"
flag on to enable this functionality.
org.springframework.beans.factory.FactoryBean that looks up a JNDI object. Exposes the object found in JNDI for bean references, e.g. for data access object's "dataSource" property in case of a javax.sql.DataSource.
The typical usage will be to register this as singleton factory (e.g. for a certain JNDI-bound DataSource) in an application context, and give bean references to application services that need it.
The default behavior is to look up the JNDI object on startup and cache it. This can be customized through the "lookupOnStartup" and "cache" properties, using a JndiObjectTargetSource underneath. Note that you need to specify a "proxyInterface" in such a scenario, since the actual JNDI object type is not known in advance.
Of course, bean classes in a Spring environment may lookup e.g. a DataSource from JNDI themselves. This class simply enables central configuration of the JNDI name, and easy switching to non-JNDI alternatives. The latter is particularly convenient for test setups, reuse in standalone clients, etc.
Note that switching to e.g. DriverManagerDataSource is just a matter of configuration: Simply replace the definition of this FactoryBean with a org.springframework.jdbc.datasource.DriverManagerDataSource definition!
org.springframework.jndi.JndiObjectTargetSource
AOP org.springframework.aop.TargetSource that provides configurable JNDI lookups for
getTarget()
calls.
Can be used as alternative to JndiObjectFactoryBean, to allow for relocating a JNDI object lazily or for each operation (see "lookupOnStartup" and "cache" properties). This is particularly useful during development, as it allows for hot restarting of the JNDI server (for example, a remote JMS server).
Example:
<bean id="queueConnectionFactoryTarget" class="org.springframework.jndi.JndiObjectTargetSource"> <property name="jndiName" value="JmsQueueConnectionFactory"/> <property name="lookupOnStartup" value="false"/> </bean> <bean id="queueConnectionFactory" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces" value="javax.jms.QueueConnectionFactory"/> <property name="targetSource" ref="queueConnectionFactoryTarget"/> </bean>
A
createQueueConnection
call on the "queueConnectionFactory" proxy will cause a lazy JNDI lookup for "JmsQueueConnectionFactory" and a subsequent delegating call to the retrieved QueueConnectionFactory's
createQueueConnection
.
Alternatively, use a JndiObjectFactoryBean with a "proxyInterface". "lookupOnStartup" and "cache" can then be specified on the JndiObjectFactoryBean, creating a JndiObjectTargetSource underneath (instead of defining separate ProxyFactoryBean and JndiObjectTargetSource beans).
org.springframework.jndi.JndiPropertySourcePropertySource implementation that reads properties from an underlying Spring JndiLocatorDelegate.
By default, the underlying
JndiLocatorDelegate
will be configured with its
"resourceRef"
property set to
true
, meaning that names looked up will automatically be prefixed with "java:comp/env/" in alignment with published
JNDI naming conventions
. To override this setting or to change the prefix, manually configure a
JndiLocatorDelegate
and provide it to one of the constructors here that accepts it. The same applies when providing custom JNDI properties. These should be specified using
JndiLocatorDelegate#setJndiEnvironment(java.util.Properties)
prior to construction of the
JndiPropertySource
.
Note that org.springframework.web.context.support.StandardServletEnvironment includes a
JndiPropertySource
by default, and any customization of the underlying JndiLocatorDelegate may be performed within an org.springframework.context.ApplicationContextInitializer or org.springframework.web.WebApplicationInitializer.
org.aopalliance.intercept.MethodInterceptor for accessing RMI services from JNDI. Typically used for RMI-IIOP but can also be used for EJB home objects (for example, a Stateful Session Bean home). In contrast to a plain JNDI lookup, this accessor also performs narrowing through PortableRemoteObject.
With conventional RMI services, this invoker is typically used with the RMI service interface. Alternatively, this invoker can also proxy a remote RMI service with a matching non-RMI business interface, i.e. an interface that mirrors the RMI service methods but does not declare RemoteExceptions. In the latter case, RemoteExceptions thrown by the RMI stub will automatically get converted to Spring's unchecked RemoteAccessException.
The JNDI environment can be specified as "jndiEnvironment" property, or be configured in a
jndi.properties
file or as system properties. For example:
<property name="jndiEnvironment"> <props> <prop key="java.naming.factory.initial">com.sun.jndi.cosnaming.CNCtxFactory</prop> <prop key="java.naming.provider.url">iiop://localhost:1050</prop> </props> </property>
org.springframework.remoting.rmi.JndiRmiProxyFactoryBean
FactoryBean for RMI proxies from JNDI.
Typically used for RMI-IIOP (CORBA), but can also be used for EJB home objects (for example, a Stateful Session Bean home). In contrast to a plain JNDI lookup, this accessor also performs narrowing through javax.rmi.PortableRemoteObject.
With conventional RMI services, this invoker is typically used with the RMI service interface. Alternatively, this invoker can also proxy a remote RMI service with a matching non-RMI business interface, i.e. an interface that mirrors the RMI service methods but does not declare RemoteExceptions. In the latter case, RemoteExceptions thrown by the RMI stub will automatically get converted to Spring's unchecked RemoteAccessException.
The JNDI environment can be specified as "jndiEnvironment" property, or be configured in a
jndi.properties
file or as system properties. For example:
<property name="jndiEnvironment"> <props> <prop key="java.naming.factory.initial">com.sun.jndi.cosnaming.CNCtxFactory</prop> <prop key="java.naming.provider.url">iiop://localhost:1050</prop> </props> </property>
org.springframework.remoting.rmi.JndiRmiServiceExporter
Service exporter which binds RMI services to JNDI. Typically used for RMI-IIOP (CORBA).
Exports services via the javax.rmi.PortableRemoteObject class. You need to run "rmic" with the "-iiop" option to generate corresponding stubs and skeletons for each exported service.
Also supports exposing any non-RMI service via RMI invokers, to be accessed via JndiRmiClientInterceptor / JndiRmiProxyFactoryBean's automatic detection of such invokers.
With an RMI invoker, RMI communication works on the RmiInvocationHandler level, needing only one stub for any service. Service interfaces do not have to extend
java.rmi.Remote
or throw
java.rmi.RemoteException
on all methods, but in and out parameters have to be serializable.
The JNDI environment can be specified as "jndiEnvironment" bean property, or be configured in a
jndi.properties
file or as system properties. For example:
<property name="jndiEnvironment"> <props> <prop key="java.naming.factory.initial">com.sun.jndi.cosnaming.CNCtxFactory</prop> <prop key="java.naming.provider.url">iiop://localhost:1050</prop> </props> </property>
org.springframework.scheduling.quartz.JobDetailFactoryBean
A Spring FactoryBean for creating a Quartz org.quartz.JobDetail instance, supporting bean-style usage for JobDetail configuration.
JobDetail(Impl)
itself is already a JavaBean but lacks sensible defaults. This class uses the Spring bean name as job name, and the Quartz default group ("DEFAULT") as job group if not specified.
Formats fields annotated with the DateTimeFormat annotation using Joda-Time.
NOTE: Spring's Joda-Time support requires Joda-Time 2.x, as of Spring 4.0.
org.springframework.format.datetime.joda.JodaTimeContextA context that holds user-specific Joda-Time settings such as the user's Chronology (calendar system) and time zone.
A
null
property value indicate the user has not specified a setting.
Configures Joda-Time's formatting system for use with Spring.
NOTE: Spring's Joda-Time support requires Joda-Time 2.x, as of Spring 4.0.
org.springframework.orm.jpa.JpaDialectSPI strategy that encapsulates certain functionality that standard JPA 2.1 does not offer, such as access to the underlying JDBC Connection. This strategy is mainly intended for standalone usage of a JPA provider; most of its functionality is not relevant when running with JTA transactions.
In general, it is recommended to derive from DefaultJpaDialect instead of implementing this interface directly. This allows for inheriting common behavior (present and future) from DefaultJpaDialect, only overriding specific hooks to plug in concrete vendor-specific behavior.
org.springframework.test.web.servlet.result.JsonPathResultMatchersFactory for assertions on the response content using JsonPath expressions.
An instance of this class is typically accessed via
MockMvcResultMatchers#jsonPath(String, Matcher)
or
MockMvcResultMatchers#jsonPath(String, Object...)
.
A RequestBodyAdvice implementation that adds support for Jackson's
@JsonView
annotation declared on a Spring MVC
@HttpEntity
or
@RequestBody
method parameter.
The deserialization view specified in the annotation will be passed in to the org.springframework.http.converter.json.MappingJackson2HttpMessageConverter which will then use it to deserialize the request body with.
Note that despite
@JsonView
allowing for more than one class to be specified, the use for a request body advice is only supported with exactly one class argument. Consider the use of a composite interface.
A ResponseBodyAdvice implementation that adds support for Jackson's
@JsonView
annotation declared on a Spring MVC
@RequestMapping
or
@ExceptionHandler
method.
The serialization view specified in the annotation will be passed in to the org.springframework.http.converter.json.MappingJackson2HttpMessageConverter which will then use it to serialize the response body.
Note that despite
@JsonView
allowing for more than one class to be specified, the use for a response body advice is only supported with exactly one class argument. Consider the use of a composite interface.
Implementation of org.springframework.http.converter.HttpMessageConverter that can read and write JSON using the JSON Binding API .
This converter can be used to bind to typed beans or untyped
HashMap
s. By default, it supports
application/json
and
application/*+json
with
UTF-8
character set.
JSP-aware (and JSTL-aware) subclass of RequestContext, allowing for population of the context from a
javax.servlet.jsp.PageContext
.
This context will detect a JSTL locale attribute in page/request/session/application scope, in addition to the fallback locale strategy provided by the base class.
org.springframework.format.datetime.standard.Jsr310DateTimeFormatAnnotationFormatterFactory
Formats fields annotated with the DateTimeFormat annotation using the JSR-310
java.time
package in JDK 8.
Simple ScopeMetadataResolver implementation that follows JSR-330 scoping rules: defaulting to prototype scope unless javax.inject.Singleton is present.
This scope resolver can be used with ClassPathBeanDefinitionScanner and AnnotatedBeanDefinitionReader for standard JSR-330 compliance. However, in practice, you will typically use Spring's rich default scoping instead - or extend this resolver with custom scoping annotations that point to extended Spring scopes.
org.springframework.web.servlet.view.JstlViewSpecialization of InternalResourceView for JSTL pages, i.e. JSP pages that use the JSP Standard Tag Library.
Exposes JSTL-specific request attributes specifying locale and resource bundle for JSTL's formatting and message tags, using Spring's locale and org.springframework.context.MessageSource.
Typical usage with InternalResourceViewResolver would look as follows, from the perspective of the DispatcherServlet context definition:
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages"/> </bean>
Every view name returned from a handler will be translated to a JSP resource (for example: "myView" -> "/WEB-INF/jsp/myView.jsp"), using this view class to enable explicit JSTL support.
The specified MessageSource loads messages from "messages.properties" etc files in the class path. This will automatically be exposed to views as JSTL localization context, which the JSTL fmt tags (message etc) will use. Consider using Spring's ReloadableResourceBundleMessageSource instead of the standard ResourceBundleMessageSource for more sophistication. Of course, any other Spring components can share the same MessageSource.
This is a separate class mainly to avoid JSTL dependencies in InternalResourceView itself. JSTL has not been part of standard J2EE up until J2EE 1.4, so we can't assume the JSTL API jar to be available on the class path.
Hint: Set the
#setExposeContextBeansAsAttributes
flag to "true" in order to make all Spring beans in the application context accessible within JSTL expressions (e.g. in a
c:out
value expression). This will also make all such beans accessible in plain
${...}
expressions in a JSP 2.0 page.
ObjectNamingStrategy
implementation that builds
ObjectName
instances from the key used in the "beans" map passed to
MBeanExporter
.
Can also check object name mappings, given as
Properties
or as
mappingLocations
of properties files. The key used to look up is the key used in
MBeanExporter
's "beans" map. If no mapping is found for a given key, the key itself is used to build an
ObjectName
.
The
<label>
tag renders a form field label in an HTML 'label' tag.
See the "formTags" showcase application that ships with the full Spring distribution for an example of this class in action.
Attribute Summary Attribute Required? Runtime Expression? DescriptioncssClass
false
HTML Optional Attribute.
cssErrorClass
false
HTML Optional Attribute. Used only when errors are present.
cssStyle
false
HTML Optional Attribute
false
HTML Standard Attribute
false
HTML Standard Attribute
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
false
HTML Standard Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
Path to errors object for data binding
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
org.springframework.scripting.config.LangNamespaceHandler
NamespaceHandler
that supports the wiring of objects backed by dynamic languages such as Groovy, JRuby and BeanShell. The following is an example (from the reference documentation) that details the wiring of a Groovy backed bean:
<lang:groovy id="messenger" refresh-check-delay="5000" script-source="classpath:Messenger.groovy"> <lang:property name="message" value="I Can Do The Frug"/> </lang:groovy>
org.springframework.web.servlet.mvc.LastModified
Supports last-modified HTTP requests to facilitate content caching. Same contract as for the Servlet API's
getLastModified
method.
Delegated to by a
org.springframework.web.servlet.HandlerAdapter#getLastModified
implementation. By default, any Controller or HttpRequestHandler within Spring's default framework can implement this interface to enable last-modified checking.
Note:
Alternative handler implementation approaches have different last-modified handling styles. For example, Spring 2.5's annotated controller approach (using
@RequestMapping
) provides last-modified support through the
org.springframework.web.context.request.WebRequest#checkNotModified
method, allowing for last-modified checking within the main handler method.
Indicates whether a bean is to be lazily initialized.
May be used on any class directly or indirectly annotated with or on methods annotated with Bean.
If this annotation is not present on a
@Component
or
@Bean
definition, eager initialization will occur. If present and set to
true
, the
@Bean
or
@Component
will not be initialized until referenced by another bean or explicitly retrieved from the enclosing org.springframework.beans.factory.BeanFactory. If present and set to
false
, the bean will be instantiated on startup by bean factories that perform eager initialization of singletons.
If Lazy is present on a Configuration class, this indicates that all
@Bean
methods within that
@Configuration
should be lazily initialized. If
@Lazy
is present and false on a
@Bean
method within a
@Lazy
-annotated
@Configuration
class, this indicates overriding the 'default lazy' behavior and that the bean should be eagerly initialized.
In addition to its role for component initialization, this annotation may also be placed on injection points marked with org.springframework.beans.factory.annotation.Autowired or javax.inject.Inject: In that context, it leads to the creation of a lazy-resolution proxy for all affected dependencies, as an alternative to using org.springframework.beans.factory.ObjectFactory or javax.inject.Provider.
org.springframework.jdbc.datasource.LazyConnectionDataSourceProxyProxy for a target DataSource, fetching actual JDBC Connections lazily, i.e. not until first creation of a Statement. Connection initialization properties like auto-commit mode, transaction isolation and read-only mode will be kept and applied to the actual JDBC Connection as soon as an actual Connection is fetched (if ever). Consequently, commit and rollback calls will be ignored if no Statements have been created.
This DataSource proxy allows to avoid fetching JDBC Connections from a pool unless actually necessary. JDBC transaction control can happen without fetching a Connection from the pool or communicating with the database; this will be done lazily on first creation of a JDBC Statement.
If you configure both a LazyConnectionDataSourceProxy and a TransactionAwareDataSourceProxy, make sure that the latter is the outermost DataSource. In such a scenario, data access code will talk to the transaction-aware DataSource, which will in turn work with the LazyConnectionDataSourceProxy.
Lazy fetching of physical JDBC Connections is particularly beneficial in a generic transaction demarcation environment. It allows you to demarcate transactions on all methods that could potentially perform data access, without paying a performance penalty if no actual data access happens.
This DataSource proxy gives you behavior analogous to JTA and a transactional JNDI DataSource (as provided by the Java EE server), even with a local transaction strategy like DataSourceTransactionManager or HibernateTransactionManager. It does not add value with Spring's JtaTransactionManager as transaction strategy.
Lazy fetching of JDBC Connections is also recommended for read-only operations with Hibernate, in particular if the chances of resolving the result in the second-level cache are high. This avoids the need to communicate with the database at all for such read-only operations. You will get the same effect with non-transactional reads, but lazy fetching of JDBC Connections allows you to still perform reads in transactions.
NOTE:
This DataSource proxy needs to return wrapped Connections (which implement the ConnectionProxy interface) in order to handle lazy fetching of an actual JDBC Connection. Use
Connection#unwrap
to retrieve the native JDBC Connection.
org.springframework.aop.TargetSource that lazily accesses a singleton bean from a org.springframework.beans.factory.BeanFactory.
Useful when a proxy reference is needed on initialization but the actual target object should not be initialized until first use. When the target bean is defined in an org.springframework.context.ApplicationContext (or a
BeanFactory
that is eagerly pre-instantiating singleton beans) it must be marked as "lazy-init" too, else it will be instantiated by said
ApplicationContext
(or
BeanFactory
) on startup.
For example:
<bean id="serviceTarget" class="example.MyService" lazy-init="true"> ... </bean> <bean id="service" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="targetSource"> <bean class="org.springframework.aop.target.LazyInitTargetSource"> <property name="targetBeanName"><idref local="serviceTarget"/></property> </bean> </property> </bean>
The "serviceTarget" bean will not get initialized until a method on the "service" proxy gets invoked.
Subclasses can extend this class and override the
#postProcessTargetObject(Object)
to perform some additional processing with the target object when it is first loaded.
TargetSourceCreator that enforces a LazyInitTargetSource for each bean that is defined as "lazy-init". This will lead to a proxy created for each of those beans, allowing to fetch a reference to such a bean without actually initializing the target bean instance.
To be registered as custom TargetSourceCreator for an auto-proxy creator, in combination with custom interceptors for specific beans or for the creation of lazy-init proxies only. For example, as autodetected infrastructure bean in an XML application context definition:
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="customTargetSourceCreators"> <list> <bean class="org.springframework.aop.framework.autoproxy.target.LazyInitTargetSourceCreator"/> </list> </property> </bean> <bean id="myLazyInitBean" class="mypackage.MyBeanClass" lazy-init="true"> ... </bean>
org.springframework.util.LinkedCaseInsensitiveMap
LinkedHashMap variant that stores String keys in a case-insensitive manner, for example for key-based access in a results table.
Preserves the original order as well as the original casing of keys, while allowing for contains, get and remove calls with any case of key.
Does
not
support
null
keys.
Abstract class that adapts a ListenableFuture parameterized over S into a
ListenableFuture
parameterized over T. All methods are delegated to the adaptee, where
#get()
,
#get(long, java.util.concurrent.TimeUnit)
, and
ListenableFutureCallback#onSuccess(Object)
call
#adapt(Object)
on the adaptee's result.
A very simple hardcoded implementation of the Expression interface that represents a string literal. It is used with CompositeStringExpression when representing a template expression which is made up of pieces - some being real expressions to be handled by an EL implementation like SpEL, and some being just textual elements.
org.springframework.context.support.LiveBeansView
Adapter for live beans view exposure, building a snapshot of current beans and their dependencies from either a local
ApplicationContext
(with a local
LiveBeansView
bean definition) or all registered ApplicationContexts (driven by the {@value #MBEAN_DOMAIN_PROPERTY_NAME} environment property).
Note: This feature is still in beta and primarily designed for use with Spring Tool Suite 3.1 and higher.
org.springframework.web.context.support.LiveBeansViewServletServlet variant of LiveBeansView's MBean exposure.
Generates a JSON snapshot for current beans and their dependencies in all ApplicationContexts that live within the current web application.
org.springframework.context.weaving.LoadTimeWeaverAwareProcessororg.springframework.beans.factory.config.BeanPostProcessor implementation that passes the context's default LoadTimeWeaver to beans that implement the LoadTimeWeaverAware interface.
org.springframework.context.ApplicationContext will automatically register this with their underlying BeanFactory, provided that a default
LoadTimeWeaver
is actually available.
Applications should not use this class directly.
org.springframework.context.annotation.LoadTimeWeavingConfigurerInterface to be implemented by org.springframework.context.annotation.Configuration classes annotated with EnableLoadTimeWeaving that wish to customize the LoadTimeWeaver instance to be used.
See org.springframework.scheduling.annotation.EnableAsync for usage examples and information on how a default
LoadTimeWeaver
is selected when this interface is not used.
org.springframework.beans.factory.FactoryBean that creates a local JCA connection factory in "non-managed" mode (as defined by the Java Connector Architecture specification). This is a direct alternative to a org.springframework.jndi.JndiObjectFactoryBean definition that obtains a connection factory handle from a Java EE server's naming environment.
The type of the connection factory is dependent on the actual connector: the connector can either expose its native API (such as a JDBC javax.sql.DataSource or a JMS javax.jms.ConnectionFactory) or follow the standard Common Client Interface (CCI), as defined by the JCA spec. The exposed interface in the CCI case is javax.resource.cci.ConnectionFactory.
In order to use this FactoryBean, you must specify the connector's
"managedConnectionFactory"
(usually configured as separate JavaBean), which will be used to create the actual connection factory reference as exposed to the application. Optionally, you can also specify a
"connectionManager"
, in order to use a custom ConnectionManager instead of the connector's default.
NOTE: In non-managed mode, a connector is not deployed on an application server, or more specificially not interacting with an application server. Consequently, it cannot use a Java EE server's system contracts: connection management, transaction management, and security management. A custom ConnectionManager implementation has to be used for applying those services in conjunction with a standalone transaction coordinator etc.
The connector will use a local ConnectionManager (included in the connector) by default, which cannot participate in global transactions due to the lack of XA enlistment. You need to specify an XA-capable ConnectionManager in order to make the connector interact with an XA transaction coordinator. Alternatively, simply use the native local transaction facilities of the exposed API (e.g. CCI local transactions), or use a corresponding implementation of Spring's PlatformTransactionManager SPI (e.g. org.springframework.jca.cci.connection.CciLocalTransactionManager) to drive local transactions.
org.springframework.scheduling.quartz.LocalDataSourceJobStoreSubclass of Quartz's JobStoreCMT class that delegates to a Spring-managed DataSource instead of using a Quartz-managed connection pool. This JobStore will be used if SchedulerFactoryBean's "dataSource" property is set.
Supports both transactional and non-transactional DataSource access. With a non-XA DataSource and local Spring transactions, a single DataSource argument is sufficient. In case of an XA DataSource and global JTA transactions, SchedulerFactoryBean's "nonTransactionalDataSource" property should be set, passing in a non-XA DataSource that will not participate in global transactions.
Operations performed by this JobStore will properly participate in any kind of Spring-managed transaction, as it uses Spring's DataSourceUtils connection handling methods that are aware of a current transaction.
Note that all Quartz Scheduler operations that affect the persistent job store should usually be performed within active transactions, as they assume to get proper locks etc.
org.springframework.orm.jpa.LocalEntityManagerFactoryBeanorg.springframework.beans.factory.FactoryBean that creates a JPA javax.persistence.EntityManagerFactory according to JPA's standard standalone bootstrap contract. This is the simplest way to set up a shared JPA EntityManagerFactory in a Spring application context; the EntityManagerFactory can then be passed to JPA-based DAOs via dependency injection. Note that switching to a JNDI lookup or to a LocalContainerEntityManagerFactoryBean definition is just a matter of configuration!
Configuration settings are usually read from a
META-INF/persistence.xml
config file, residing in the class path, according to the JPA standalone bootstrap contract. Additionally, most JPA providers will require a special VM agent (specified on JVM startup) that allows them to instrument application classes. See the Java Persistence API specification and your provider documentation for setup details.
This EntityManagerFactory bootstrap is appropriate for standalone applications which solely use JPA for data access. If you want to set up your persistence provider for an external DataSource and/or for global transactions which span multiple resources, you will need to either deploy it into a full Java EE application server and access the deployed EntityManagerFactory via JNDI, or use Spring's LocalContainerEntityManagerFactoryBean with appropriate configuration for local setup according to JPA's container contract.
Note: This FactoryBean has limited configuration power in terms of what configuration it is able to pass to the JPA provider. If you need more flexible configuration, for example passing a Spring-managed JDBC DataSource to the JPA provider, consider using Spring's more powerful LocalContainerEntityManagerFactoryBean instead.
NOTE: Spring's JPA support requires JPA 2.1 or higher, as of Spring 5.0. JPA 1.0/2.0 based applications are still supported; however, a JPA 2.1 compliant persistence provider is needed at runtime.
org.springframework.remoting.jaxws.LocalJaxWsServiceFactory
Factory for locally defined JAX-WS javax.xml.ws.Service references. Uses the JAX-WS
javax.xml.ws.Service#create
factory API underneath.
Serves as base class for LocalJaxWsServiceFactoryBean as well as JaxWsPortClientInterceptor and JaxWsPortProxyFactoryBean.
org.springframework.remoting.jaxws.LocalJaxWsServiceFactoryBeanorg.springframework.beans.factory.FactoryBean for locally defined JAX-WS Service references. Uses LocalJaxWsServiceFactory's facilities underneath.
Alternatively, JAX-WS Service references can be looked up in the JNDI environment of the Java EE container.
org.springframework.orm.hibernate5.LocalSessionFactoryBuilderA Spring-provided extension of the standard Hibernate Configuration class, adding SpringSessionContext as a default and providing convenient ways to specify a DataSource and an application class loader.
This is designed for programmatic use, e.g. in
@Bean
factory methods. Consider using LocalSessionFactoryBean for XML bean definition files.
Compatible with Hibernate 5.0/5.1 as well as 5.2, as of Spring 4.3.
org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBeanConvenient FactoryBean for local Stateless Session Bean (SLSB) proxies. Designed for EJB 2.x, but works for EJB 3 Session Beans as well.
See org.springframework.jndi.JndiObjectLocator for info on how to specify the JNDI location of the target EJB.
If you want control over interceptor chaining, use an AOP ProxyFactoryBean with LocalSlsbInvokerInterceptor rather than rely on this class.
In a bean container, this class is normally best used as a singleton. However, if that bean container pre-instantiates singletons (as do the XML ApplicationContext variants) you may have a problem if the bean container is loaded before the EJB container loads the target EJB. That is because by default the JNDI lookup will be performed in the init method of this class and cached, but the EJB will not have been bound at the target location yet. The best solution is to set the "lookupHomeOnStartup" property to "false", in which case the home will be fetched on first access to the EJB. (This flag is only true by default for backwards compatibility reasons).
org.springframework.validation.beanvalidation.LocalValidatorFactoryBean
This is the central class for
javax.validation
(JSR-303) setup in a Spring application context: It bootstraps a
javax.validation.ValidationFactory
and exposes it through the Spring org.springframework.validation.Validator interface as well as through the JSR-303 javax.validation.Validator interface and the javax.validation.ValidatorFactory interface itself.
When talking to an instance of this bean through the Spring or JSR-303 Validator interfaces, you'll be talking to the default Validator of the underlying ValidatorFactory. This is very convenient in that you don't have to perform yet another call on the factory, assuming that you will almost always use the default Validator anyway. This can also be injected directly into any target dependency of type org.springframework.validation.Validator!
As of Spring 5.0, this class requires Bean Validation 1.1+, with special support for Hibernate Validator 5.x
(see
#setValidationMessageSource
). This class is also runtime-compatible with Bean Validation 2.0 and Hibernate Validator 6.0, with one special note: If you'd like to call BV 2.0's
getClockProvider()
method, obtain the native
ValidatorFactory
through
#unwrap(ValidatorFactory.class)
and call the
getClockProvider()
method on the returned native reference there.
This class is also being used by Spring's MVC configuration namespace, in case of the
javax.validation
API being present but no explicit Validator having been configured.
Implementation of ParameterNameDiscoverer that uses the LocalVariableTable information in the method attributes to discover parameter names. Returns
null
if the class file was compiled without debug information.
Uses ObjectWeb's ASM library for analyzing class files. Each discoverer instance caches the ASM discovered information for each introspected Class, in a thread-safe manner. It is recommended to reuse ParameterNameDiscoverer instances as far as possible.
org.springframework.beans.propertyeditors.LocaleEditor
Editor for
java.util.Locale
, to directly populate a Locale property.
Expects the same syntax as Locale's
toString
, i.e. language + optionally country + optionally variant, separated by "_" (e.g. "en", "en_US"). Also accepts spaces as separators, as alternative to underscores.
Class that models an arbitrary location in a Resource.
Typically used to track the location of problematic or erroneous metadata in XML configuration files. For example, a
source
location might be 'The bean defined on line 76 of beans.properties has an invalid Class'; another source might be the actual DOM Element from a parsed XML org.w3c.dom.Document; or the source object might simply be
null
.
An annotation that indicates 'lookup' methods, to be overridden by the container to redirect them back to the org.springframework.beans.factory.BeanFactory for a
getBean
call. This is essentially an annotation-based version of the XML
lookup-method
attribute, resulting in the same runtime arrangement.
The resolution of the target bean can either be based on the return type (
getBean(Class)
) or on a suggested bean name (
getBean(String)
), in both cases passing the method's arguments to the
getBean
call for applying them as target factory method arguments or constructor arguments.
Such lookup methods can have default (stub) implementations that will simply get replaced by the container, or they can be declared as abstract - for the container to fill them in at runtime. In both cases, the container will generate runtime subclasses of the method's containing class via CGLIB, which is why such lookup methods can only work on beans that the container instantiates through regular constructors: i.e. lookup methods cannot get replaced on beans returned from factory methods where we cannot dynamically provide a subclass for them.
Concrete limitations in typical Spring configuration scenarios:
When used with component scanning or any other mechanism that filters out abstract beans, provide stub implementations of your lookup methods to be able to declare them as concrete classes. And please remember that lookup methods won't work on beans returned from
@Bean
methods in configuration classes; you'll have to resort to
@Inject Provider<TargetBean>
or the like instead.
Represents an override of a method that looks up an object in the same IoC context.
Methods eligible for lookup override must not have arguments.
org.springframework.context.annotation.MBeanExportConfiguration
@Configuration
class that registers a AnnotationMBeanExporter bean.
This configuration class is automatically imported when using the EnableMBeanExport annotation. See its javadoc for complete usage details.
org.springframework.jmx.access.MBeanProxyFactoryBeanCreates a proxy to a managed resource running either locally or remotely. The "proxyInterface" property defines the interface that the generated proxy is supposed to implement. This interface should define methods and properties that correspond to operations and attributes in the management interface of the resource you wish to proxy.
There is no need for the managed resource to implement the proxy interface, although you may find it convenient to do. It is not required that every operation and attribute in the management interface is matched by a corresponding property or method in the proxy interface.
Attempting to invoke or access any method or property on the proxy interface that does not correspond to the management interface will lead to an
InvalidInvocationException
.
FactoryBean that obtains an javax.management.MBeanServer reference through the standard JMX 1.2 javax.management.MBeanServerFactory API (which is available on JDK 1.5 or as part of a JMX 1.2 provider). Exposes the
MBeanServer
for bean references.
By default,
MBeanServerFactoryBean
will always create a new
MBeanServer
even if one is already running. To have the
MBeanServerFactoryBean
attempt to locate a running
MBeanServer
first, set the value of the "locateExistingServerIfPossible" property to "true".
Class-level annotation that indicates to register instances of a class with a JMX server, corresponding to the
ManagedResource
attribute.
Note: This annotation is marked as inherited, allowing for generic management-aware base classes. In such a scenario, it is recommended to not specify an object name value since this would lead to naming collisions in case of multiple subclasses getting registered.
org.springframework.validation.MapBindingResultMap-based implementation of the BindingResult interface, supporting registration and evaluation of binding errors on Map attributes.
Can be used as errors holder for custom binding onto a Map, for example when invoking a Validator for a Map object.
org.springframework.jdbc.datasource.lookup.MapDataSourceLookupSimple DataSourceLookup implementation that relies on a map for doing lookups.
Useful for testing environments or applications that need to match arbitrary String names to target DataSource objects.
org.springframework.web.method.annotation.MapMethodProcessorResolves Map method arguments and handles Map return values.
A Map return value can be interpreted in more than one ways depending on the presence of annotations like
@ModelAttribute
or
@ResponseBody
. Therefore this handler should be configured after the handlers that support these annotations.
Implementation of org.springframework.http.converter.HttpMessageConverter that can read and write CBOR data format using the dedicated Jackson 2.x extension .
By default, this converter supports
"application/cbor"
media type. This can be overridden by setting the
supportedMediaTypes
property.
The default constructor uses the default configuration provided by Jackson2ObjectMapperBuilder.
Compatible with Jackson 2.9 and higher.
org.springframework.http.converter.json.MappingJackson2HttpMessageConverterImplementation of org.springframework.http.converter.HttpMessageConverter that can read and write JSON using Jackson 2.x's ObjectMapper.
This converter can be used to bind to typed beans, or untyped
HashMap
instances.
By default, this converter supports
application/json
and
application/*+json
with
UTF-8
character set. This can be overridden by setting the
supportedMediaTypes
property.
The default constructor uses the default configuration provided by Jackson2ObjectMapperBuilder.
Compatible with Jackson 2.9 and higher, as of Spring 5.0.
org.springframework.web.servlet.view.json.MappingJackson2JsonViewSpring MVC View that renders JSON content by serializing the model for the current request using Jackson 2's ObjectMapper.
By default, the entire contents of the model map (with the exception of framework-specific classes) will be encoded as JSON. If the model contains only one key, you can have it extracted encoded as JSON alone via
#setExtractValueFromSingleKeyModel
.
The default constructor uses the default configuration provided by Jackson2ObjectMapperBuilder.
Compatible with Jackson 2.6 and higher, as of Spring 4.3.
org.springframework.jms.support.converter.MappingJackson2MessageConverter
Message converter that uses Jackson 2.x to convert messages to and from JSON. Maps an object to a BytesMessage, or to a TextMessage if the
targetType
is set to
MessageType#TEXT
. Converts from a TextMessage or BytesMessage to an object.
It customizes Jackson's default properties with the following ones:
MapperFeature#DEFAULT_VIEW_INCLUSION
is disabled
DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES
is disabled
Compatible with Jackson 2.6 and higher, as of Spring 4.3.
org.springframework.http.converter.smile.MappingJackson2SmileHttpMessageConverterImplementation of org.springframework.http.converter.HttpMessageConverter that can read and write Smile data format ("binary JSON") using the dedicated Jackson 2.x extension .
By default, this converter supports
"application/x-jackson-smile"
media type. This can be overridden by setting the
supportedMediaTypes
property.
The default constructor uses the default configuration provided by Jackson2ObjectMapperBuilder.
Compatible with Jackson 2.9 and higher.
org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverterImplementation of org.springframework.http.converter.HttpMessageConverter that can read and write XML using Jackson 2.x extension component for reading and writing XML encoded data .
By default, this converter supports
application/xml
,
text/xml
, and
application/*+xml
with
UTF-8
character set. This can be overridden by setting the
supportedMediaTypes
property.
The default constructor uses the default configuration provided by Jackson2ObjectMapperBuilder.
Compatible with Jackson 2.9 and higher, as of Spring 5.0.
org.springframework.web.servlet.view.xml.MappingJackson2XmlViewSpring MVC View that renders XML content by serializing the model for the current request using Jackson 2's XmlMapper.
The Object to be serialized is supplied as a parameter in the model. The first serializable entry is used. Users can either specify a specific entry in the model via the
sourceKey
property.
The default constructor uses the default configuration provided by Jackson2ObjectMapperBuilder.
Compatible with Jackson 2.6 and higher, as of Spring 4.3.
org.springframework.http.converter.json.MappingJacksonValueA simple holder for the POJO to serialize via MappingJackson2HttpMessageConverter along with further serialization instructions to be passed in to the converter.
On the server side this wrapper is added with a
ResponseBodyInterceptor
after content negotiation selects the converter to use but before the write.
On the client side, simply wrap the POJO and pass it in to the
RestTemplate
.
Reusable query in which concrete subclasses must implement the abstract mapRow(ResultSet, int) method to convert each row of the JDBC ResultSet into an object.
Simplifies MappingSqlQueryWithParameters API by dropping parameters and context. Most subclasses won't care about parameters. If you don't use contextual information, subclass this instead of MappingSqlQueryWithParameters.
org.springframework.http.converter.xml.MarshallingHttpMessageConverterImplementation of org.springframework.http.converter.HttpMessageConverter that can read and write XML using Spring's Marshaller and Unmarshaller abstractions.
This converter requires a
Marshaller
and
Unmarshaller
before it can be used. These can be injected by the
constructor
or
bean properties
.
By default, this converter supports
text/xml
and
application/xml
. This can be overridden by setting the
supportedMediaTypes
property.
Implementation of MessageConverter that can read and write XML using Spring's Marshaller and Unmarshaller abstractions.
This converter requires a
Marshaller
and
Unmarshaller
before it can be used. These can be injected by the
constructor
or
bean properties
.
Source implementation that uses a Marshaller.Can be constructed with a
Marshaller
and an object to be marshalled.
Even though
MarshallingSource
extends from
SAXSource
, calling the methods of
SAXSource
is
not supported
. In general, the only supported operation on this class is to use the
XMLReader
obtained via
#getXMLReader()
to parse the input source obtained via
. Calling
#setXMLReader(XMLReader)
or
#setInputSource(InputSource)
will result in
UnsupportedOperationException
s.
Spring-MVC View that allows for response context to be rendered as the result of marshalling by a Marshaller.
The Object to be marshalled is supplied as a parameter in the model and then
detected
during response rendering. Users can either specify a specific entry in the model via the
sourceKey
property or have Spring locate the Source object.
Very simple implementation of TransactionAttributeSource which will always return the same TransactionAttribute for all methods fed to it. The TransactionAttribute may be specified, but will otherwise default to PROPAGATION_REQUIRED. This may be used in the cases where you want to use the same transaction attribute with all methods being handled by a transaction interceptor.
org.springframework.web.bind.annotation.MatrixVariableAnnotation which indicates that a method parameter should be bound to a name-value pair within a path segment. Supported for RequestMapping annotated handler methods in Servlet environments.
If the method parameter type is java.util.Map and a matrix variable name is specified, then the matrix variable value is converted to a java.util.Map assuming an appropriate conversion strategy is available.
If the method parameter is java.util.Map or org.springframework.util.MultiValueMap and a variable name is not specified, then the map is populated with all matrix variable names and values.
org.springframework.web.reactive.result.method.annotation.MatrixVariableMapMethodArgumentResolverResolves arguments of type Map annotated with where
org.springframework.web.servlet.mvc.method.annotation.MatrixVariableMapMethodArgumentResolverResolves arguments of type Map annotated with where
org.springframework.web.reactive.result.method.annotation.MatrixVariableMethodArgumentResolverResolves arguments annotated with MatrixVariable.
If the method parameter is of type Map it will by resolved by MatrixVariableMapMethodArgumentResolver instead unless the annotation specifies a name in which case it is considered to be a single attribute of type map (vs multiple attributes collected in a map).
org.springframework.web.servlet.mvc.method.annotation.MatrixVariableMethodArgumentResolverResolves arguments annotated with MatrixVariable.
If the method parameter is of type Map it will by resolved by MatrixVariableMapMethodArgumentResolver instead unless the annotation specifies a name in which case it is considered to be a single attribute of type map (vs multiple attributes collected in a map).
org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor
Post-processor callback interface for
merged
bean definitions at runtime. BeanPostProcessor implementations may implement this sub-interface in order to post-process the merged bean definition (a processed copy of the original bean definition) that the Spring
BeanFactory
uses to create a bean instance.
The
#postProcessMergedBeanDefinition
method may for example introspect the bean definition in order to prepare some cached metadata before post-processing actual instances of a bean. It is also allowed to modify the bean definition but
only
for definition properties which are actually intended for concurrent modification. Essentially, this only applies to operations defined on the RootBeanDefinition itself but not to the properties of its base classes.
Contract for mapping conditions to messages.
Message conditions can be combined (e.g. type + method-level conditions), matched to a specific Message, as well as compared to each other in the context of a Message to determine which one matches a request more closely.
Creates a JMS message given a Session.
The
Session
typically is provided by an instance of the JmsTemplate class.
Implementations
do not
need to concern themselves with checked
JMSExceptions
(from the '
javax.jms
' package) that may be thrown from operations they attempt. The
JmsTemplate
will catch and handle these
JMSExceptions
appropriately.
Message listener adapter that delegates the handling of messages to target listener methods via reflection, with flexible message type conversion. Allows listener methods to operate on message content types, completely independent from the JMS API.
By default, the content of incoming JMS messages gets extracted before being passed into the target listener method, to let the target method operate on message content types such as String or byte array instead of the raw Message. Message type conversion is delegated to a Spring JMS MessageConverter. By default, a SimpleMessageConverter will be used. (If you do not want such automatic message conversion taking place, then be sure to set the
MessageConverter
to
null
.)
If a target listener method returns a non-null object (typically of a message content type such as
String
or byte array), it will get wrapped in a JMS
Message
and sent to the response destination (either the JMS "reply-to" destination or a
specified default
).
Note: The sending of response messages is only available when using the SessionAwareMessageListener entry point (typically through a Spring message listener container). Usage as standard JMS MessageListener does not support the generation of response messages.
Find below some examples of method signatures compliant with this adapter class. This first example handles all
Message
types and gets passed the contents of each
Message
type as an argument. No
Message
will be sent back as all of these methods return
void
.
public interface MessageContentsDelegate { void handleMessage(String text); void handleMessage(Map map); void handleMessage(byte[] bytes); void handleMessage(Serializable obj); }
This next example handles all
Message
types and gets passed the actual (raw)
Message
as an argument. Again, no
Message
will be sent back as all of these methods return
void
.
public interface RawMessageDelegate { void handleMessage(TextMessage message); void handleMessage(MapMessage message); void handleMessage(BytesMessage message); void handleMessage(ObjectMessage message); }
This next example illustrates a
Message
delegate that just consumes the
String
contents of javax.jms.TextMessage. Notice also how the name of the
Message
handling method is different from the
original
(this will have to be configured in the attandant bean definition). Again, no
Message
will be sent back as the method returns
void
.
public interface TextMessageContentDelegate { void onMessage(String text); }
This final example illustrates a
Message
delegate that just consumes the
String
contents of javax.jms.TextMessage. Notice how the return type of this method is
String
: This will result in the configured MessageListenerAdapter sending a javax.jms.TextMessage in response.
public interface ResponsiveTextMessageContentDelegate { String handleMessage(String text); }
For further examples and discussion please do refer to the Spring reference documentation which describes this class (and it's attendant XML configuration) in detail.
org.springframework.messaging.handler.annotation.MessageMapping
Annotation for mapping a Message onto message-handling methods by matching to the message destination. This annotation can also be used on the type-level in which case it defines a common destination prefix or pattern for all method-level annotations including method-level org.springframework.messaging.simp.annotation.SubscribeMapping annotations.
Handler methods which are annotated with this annotation are allowed to have flexible signatures. They may have arguments of the following types, in arbitrary order:
A return value will get wrapped as a message and sent to a default response destination or to a custom destination specified with an SendTo method-level annotation. Such a response may also be provided asynchronously via a org.springframework.util.concurrent.ListenableFuture return type or a corresponding JDK 8 java.util.concurrent.CompletableFuture / java.util.concurrent.CompletionStage handle.
STOMP over WebSocket
An SendTo annotation is not strictly required — by default the message will be sent to the same destination as the incoming message but with an additional prefix (
"/topic"
by default). It is also possible to use the org.springframework.messaging.simp.annotation.SendToUser annotation to have the message directed to a specific user if connected. The return value is converted with a org.springframework.messaging.converter.MessageConverter.
NOTE:
When using controller interfaces (e.g. for AOP proxying), make sure to consistently put
all
your mapping annotations - such as
@MessageMapping
and
@SubscribeMapping
- on the controller
interface
rather than on the implementation class.
To be used with JmsTemplate's send method that convert an object to a message. It allows for further modification of the message after it has been processed by the converter. This is useful for setting of JMS Header and Properties.
This often as an anonymous class within a method implementation.
org.springframework.context.MessageSourceAwareInterface to be implemented by any object that wishes to be notified of the MessageSource (typically the ApplicationContext) that it runs in.
Note that the MessageSource can usually also be passed on as bean reference (to arbitrary bean properties or constructor arguments), because it is defined as bean with name "messageSource" in the application context.
org.springframework.context.support.MessageSourceSupportBase class for message source implementations, providing support infrastructure such as java.text.MessageFormat handling but not implementing concrete methods defined in the org.springframework.context.MessageSource.
AbstractMessageSource derives from this class, providing concrete
getMessage
implementations that delegate to a central template method for message code resolution.
The
<message>
tag looks up a message in the scope of this page. Messages are resolved using the ApplicationContext and thus support internationalization.
Detects an HTML escaping setting, either on this tag instance, the page level, or the
web.xml
level. Can also apply JavaScript escaping.
If "code" isn't set or cannot be resolved, "text" will be used as default message. Thus, this tag can also be used for HTML escaping of any texts.
Message arguments can be specified via the
arguments
attribute or by using nested
<spring:argument>
tags.
Represents a Spring-managed bean with cross-cutting functionality to be applied to one or more Spring beans with annotation-based message handling methods.
Component stereotypes such as org.springframework.stereotype.Controller with annotation handler methods often need cross-cutting functionality across all or a subset of such annotated components. A primary example of this is the need for "global" annotated exception handler methods but the concept applies more generally.
org.springframework.jdbc.support.MetaDataAccessExceptionException indicating that something went wrong during JDBC metadata lookup.
This is a checked exception since we want it to be caught, logged and handled rather than cause the application to fail. Failure to read JDBC metadata is usually not a fatal problem.
org.springframework.jmx.export.naming.MetadataNamingStrategy
An implementation of the ObjectNamingStrategy interface that reads the
ObjectName
from the source-level metadata. Falls back to the bean key (bean name) if no
ObjectName
can be found in source-level metadata.
Uses the JmxAttributeSource strategy interface, so that metadata can be read using any supported implementation. Out of the box, org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource introspects a well-defined set of Java 5 annotations that come with Spring.
org.springframework.messaging.handler.annotation.support.MethodArgumentTypeMismatchExceptionException that indicates that a method argument has not the expected type.
org.springframework.context.expression.MethodBasedEvaluationContextA method-based org.springframework.expression.EvaluationContext that provides explicit support for method-based invocations.
Expose the actual method arguments using the following aliases:
AbstractReflectiveMBeanInfoAssembler
subclass that allows method names to be explicitly excluded as MBean operations and attributes.
Any method not explicitly excluded from the management interface will be exposed to JMX. JavaBean getters and setters will automatically be exposed as JMX attributes.
You can supply an array of method names via the
ignoredMethods
property. If you have multiple beans and you wish each bean to use a different set of method names, then you can map bean keys (that is the name used to pass the bean to the
MBeanExporter
) to a list of method names using the
ignoredMethodMappings
property.
If you specify values for both
ignoredMethodMappings
and
ignoredMethods
, Spring will attempt to find method names in the mappings first. If no method names for the bean are found, it will use the method names defined by
ignoredMethods
.
Intercepts calls on an interface on its way to the target. These are nested "on top" of the target.
The user should implement the
#invoke(MethodInvocation)
method to modify the original behavior. E.g. the following class implements a tracing interceptor (traces all the calls on the intercepted method(s)):
class TracingInterceptor implements MethodInterceptor { Object invoke(MethodInvocation i) throws Throwable { System.out.println("method "+i.getMethod()+" is called on "+ i.getThis()+" with args "+i.getArguments()); Object ret=i.proceed(); System.out.println("method "+i.getMethod()+" returns "+ret); return ret; } }
org.aopalliance.intercept.MethodInvocation
Description of an invocation to a method, given to an interceptor upon method-call.
A method invocation is a joinpoint and can be intercepted by a method interceptor.
org.springframework.aop.aspectj.MethodInvocationProceedingJoinPointImplementation of AspectJ ProceedingJoinPoint interface wrapping an AOP Alliance MethodInvocation.
Note
: the
getThis()
method returns the current Spring AOP proxy. The
getTarget()
method returns the current Spring AOP target (which may be
null
if there is no target), and is a plain POJO without any advice.
If you want to call the object and have the advice take effect, use
getThis()
.
A common example is casting the object to an introduced interface in the implementation of an introduction.
Of course there is no such distinction between target and proxy in AspectJ.
org.springframework.beans.factory.config.MethodInvokingBeanSimple method invoker bean: just invoking a target method, not expecting a result to expose to the container (in contrast to MethodInvokingFactoryBean).
This invoker supports any kind of target method. A static method may be specified by setting the
targetMethod
property to a String representing the static method name, with
targetClass
specifying the Class that the static method is defined on. Alternatively, a target instance method may be specified, by setting the
targetObject
property as the target object, and the
targetMethod
property as the name of the method to call on that target object. Arguments for the method invocation may be specified by setting the
arguments
property.
This class depends on
#afterPropertiesSet()
being called once all properties have been set, as per the InitializingBean contract.
An example (in an XML based bean factory definition) of a bean definition which uses this class to call a static initialization method:
<bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingBean"> <property name="staticMethod" value="com.whatever.MyClass.init"/> </bean>
An example of calling an instance method to start some server bean:
<bean id="myStarter" class="org.springframework.beans.factory.config.MethodInvokingBean"> <property name="targetObject" ref="myServer"/> <property name="targetMethod" value="start"/> </bean>
org.springframework.beans.factory.config.MethodInvokingFactoryBean
FactoryBean which returns a value which is the result of a static or instance method invocation. For most use cases it is better to just use the container's built-in factory method support for the same purpose, since that is smarter at converting arguments. This factory bean is still useful though when you need to call a method which doesn't return any value (for example, a static class method to force some sort of initialization to happen). This use case is not supported by factory methods, since a return value is needed to obtain the bean instance.
Note that as it is expected to be used mostly for accessing factory methods, this factory by default operates in a
singleton
fashion. The first request to
#getObject
by the owning bean factory will cause a method invocation, whose return value will be cached for subsequent requests. An internal
singleton
property may be set to "false", to cause this factory to invoke the target method each time it is asked for an object.
NOTE: If your target method does not produce a result to expose, consider MethodInvokingBean instead, which avoids the type determination and lifecycle limitations that this MethodInvokingFactoryBean comes with.
This invoker supports any kind of target method. A static method may be specified by setting the
targetMethod
property to a String representing the static method name, with
targetClass
specifying the Class that the static method is defined on. Alternatively, a target instance method may be specified, by setting the
targetObject
property as the target object, and the
targetMethod
property as the name of the method to call on that target object. Arguments for the method invocation may be specified by setting the
arguments
property.
This class depends on
#afterPropertiesSet()
being called once all properties have been set, as per the InitializingBean contract.
An example (in an XML based bean factory definition) of a bean definition which uses this class to call a static factory method:
<bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="staticMethod" value="com.whatever.MyClassFactory.getInstance"/> </bean>
An example of calling a static method then an instance method to get at a Java system property. Somewhat verbose, but it works.
<bean id="sysProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetClass" value="java.lang.System"/> <property name="targetMethod" value="getProperties"/> </bean> <bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"> <property name="targetObject" ref="sysProps"/> <property name="targetMethod" value="getProperty"/> <property name="arguments" value="java.version"/> </bean>
org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean
org.springframework.beans.factory.FactoryBean that exposes a org.quartz.JobDetail object which delegates job execution to a specified (static or non-static) method. Avoids the need for implementing a one-line Quartz Job that just invokes an existing service method on a Spring-managed target bean.
Inherits common configuration properties from the MethodInvoker base class, such as
"targetObject"
and
"targetMethod"
, adding support for lookup of the target bean by name through the
"targetBeanName"
property (as alternative to specifying a "targetObject" directly, allowing for non-singleton target objects).
Supports both concurrently running jobs and non-currently running jobs through the "concurrent" property. Jobs created by this MethodInvokingJobDetailFactoryBean are by default volatile and durable (according to Quartz terminology).
NOTE: JobDetails created via this FactoryBean are not serializable and thus not suitable for persistent job stores. You need to implement your own Quartz Job as a thin wrapper for each case where you want a persistent job to delegate to a specific service method.
Compatible with Quartz 2.1.4 and higher, as of Spring 4.1.
org.springframework.scheduling.support.MethodInvokingRunnableAdapter that implements the Runnable interface as a configurable method invocation based on Spring's MethodInvoker.
Inherits common configuration properties from org.springframework.util.MethodInvoker.
org.springframework.aop.support.MethodMatchersStatic utility methods for composing MethodMatcher.
A MethodMatcher may be evaluated statically (based on method and target class) or need further evaluation dynamically (based on arguments at the time of method invocation).
org.springframework.jmx.export.assembler.MethodNameBasedMBeanInfoAssembler
Subclass of
AbstractReflectiveMBeanInfoAssembler
that allows to specify method names to be exposed as MBean operations and attributes. JavaBean getters and setters will automatically be exposed as JMX attributes.
You can supply an array of method names via the
managedMethods
property. If you have multiple beans and you wish each bean to use a different set of method names, then you can map bean keys (that is the name used to pass the bean to the
MBeanExporter
) to a list of method names using the
methodMappings
property.
If you specify values for both
methodMappings
and
managedMethods
, Spring will attempt to find method names in the mappings first. If no method names for the bean are found, it will use the method names defined by
managedMethods
.
Set of method overrides, determining which, if any, methods on a managed object the Spring IoC container will override at runtime.
The currently supported MethodOverride variants are LookupOverride and ReplaceOverride.
org.springframework.beans.factory.support.MethodReplacerInterface to be implemented by classes that can reimplement any method on an IoC-managed object: the Method Injection form of Dependency Injection.
Such methods may be (but need not be) abstract, in which case the container will create a concrete subclass to instantiate.
org.springframework.validation.beanvalidation.MethodValidationInterceptorAn AOP Alliance MethodInterceptor implementation that delegates to a JSR-303 provider for performing method-level validation on annotated methods.
Applicable methods have JSR-303 constraint annotations on their parameters and/or on their return value (in the latter case specified at the method level, typically as inline annotation).
E.g.:
public @NotNull Object myValidMethod(@NotNull String arg1, @Max(10) int arg2)
Validation groups can be specified through Spring's Validated annotation at the type level of the containing target class, applying to all public service methods of that class. By default, JSR-303 will validate against its default group only.
As of Spring 5.0, this functionality requires a Bean Validation 1.1 provider.
org.springframework.validation.beanvalidation.MethodValidationPostProcessorA convenient BeanPostProcessor implementation that delegates to a JSR-303 provider for performing method-level validation on annotated methods.
Applicable methods have JSR-303 constraint annotations on their parameters and/or on their return value (in the latter case specified at the method level, typically as inline annotation), e.g.:
public @NotNull Object myValidMethod(@NotNull String arg1, @Max(10) int arg2)
Target classes with such annotated methods need to be annotated with Spring's Validated annotation at the type level, for their methods to be searched for inline constraint annotations. Validation groups can be specified through
@Validated
as well. By default, JSR-303 will validate against its default group only.
As of Spring 5.0, this functionality requires a Bean Validation 1.1 provider.
org.springframework.mail.javamail.MimeMailMessageImplementation of the MailMessage interface for a JavaMail MIME message, to let message population code interact with a simple message or a MIME message through a common interface.
Uses a MimeMessageHelper underneath. Can either be created with a MimeMessageHelper instance or with a JavaMail MimeMessage instance.
org.springframework.web.bind.MissingPathVariableException
ServletRequestBindingException subclass that indicates that a path variable expected in the method parameters of an
@RequestMapping
method is not present among the URI variables extracted from the URL. Typically that means the URI template does not match the path variable name declared on the method parameter.
Raised when the part of a "multipart/form-data" request identified by its name cannot be found.
This may be because the request is not a multipart/form-data request, because the part is not present in the request, or because the web application is not configured correctly for processing multipart requests, e.g. no MultipartResolver.
org.springframework.mock.web.MockExpressionEvaluatorMock implementation of the JSP 2.0 javax.servlet.jsp.el.ExpressionEvaluator interface, delegating to the Apache JSTL ExpressionEvaluatorManager. Only necessary for testing applications when testing custom JSP tags.
Note that the Apache JSTL implementation (jstl.jar, standard.jar) has to be available on the class path to use this expression evaluator.
org.springframework.mock.web.MockFilterChainMock implementation of the javax.servlet.FilterChain interface.
A MockFilterChain can be configured with one or more filters and a Servlet to invoke. The first time the chain is called, it invokes all filters and the Servlet, and saves the request and response. Subsequent invocations raise an IllegalStateException unless
#reset()
is called.
Mock implementation of the javax.servlet.FilterConfig interface.
Used for testing the web framework; also useful for testing custom javax.servlet.Filter implementations.
org.springframework.mock.web.MockMultipartHttpServletRequestMock implementation of the org.springframework.web.multipart.MultipartHttpServletRequest interface.
As of Spring 5.0, this set of mocks is designed on a Servlet 4.0 baseline.
Useful for testing application controllers that access multipart uploads. MockMultipartFile can be used to populate these mock requests with files.
org.springframework.test.web.servlet.MockMvcBuilderSupportBase class for MockMvc builder implementations, providing the capability to create a MockMvc instance.
org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder, which derives from this class, provides a concrete
build
method, and delegates to abstract methods to obtain a WebApplicationContext.
The main class to import in order to access all available MockMvcBuilders. Eclipse Users
Consider adding this class as a Java editor favorite. To navigate to this setting, open the Preferences and type "favorites".
org.springframework.test.web.client.MockMvcClientHttpRequestFactoryA ClientHttpRequestFactory for requests executed via MockMvc.
As of 5.0 this class also implements org.springframework.http.client.AsyncClientHttpRequestFactory. However note that org.springframework.web.client.AsyncRestTemplate and related classes have been deprecated at the same time.
org.springframework.test.web.servlet.htmlunit.webdriver.MockMvcHtmlUnitDriverBuilder
MockMvcHtmlUnitDriverBuilder
simplifies the building of an HtmlUnitDriver that delegates to MockMvc and optionally delegates to an actual connection for specific requests.
By default, the driver will delegate to
MockMvc
to handle requests to
localhost
and to a WebClient to handle any other URL (i.e. to perform an actual HTTP request).
Static factory methods for ResultHandler-based result actions. Eclipse Users
Consider adding this class as a Java editor favorite. To navigate to this setting, open the Preferences and type "favorites".
org.springframework.test.web.servlet.htmlunit.MockMvcWebClientBuilder
MockMvcWebClientBuilder
simplifies the creation of an HtmlUnit WebClient that delegates to a MockMvc instance.
The
MockMvc
instance used by the builder may be
supplied directly
or created transparently from a
WebApplicationContext
.
MockMvcWebConnection
enables MockMvc to transform a WebRequest into a WebResponse.
This is the core integration with HtmlUnit .
Example usage can be seen below.
WebClient webClient = new WebClient(); MockMvc mockMvc = ... MockMvcWebConnection webConnection = new MockMvcWebConnection(mockMvc, webClient); webClient.setWebConnection(webConnection); // Use webClient as normal ...
org.springframework.test.web.servlet.htmlunit.MockMvcWebConnectionBuilderSupport
Support class that simplifies the creation of a WebConnection that uses MockMvc and optionally delegates to a real WebConnection for specific requests.
The default is to use MockMvc for requests to
localhost
and otherwise use a real WebConnection.
Mock implementation of the javax.servlet.jsp.PageContext interface. Only necessary for testing applications when testing custom JSP tags.
Note: Expects initialization via the constructor rather than via the
PageContext.initialize
method. Does not support writing to a JspWriter, request dispatching, or
handlePageException
calls.
Simple PropertySource implementation for use in testing. Accepts a user-provided Properties object, or if omitted during construction, the implementation will initialize its own. The
#setProperty
and
#withProperty
methods are exposed for convenience, for example:
PropertySource<?> source = new MockPropertySource().withProperty("foo", "bar");
org.springframework.test.web.client.match.MockRestRequestMatchers
Static factory methods for RequestMatcher classes. Typically used to provide input for
MockRestServiceServer#expect(RequestMatcher)
. Eclipse Users
Consider adding this class as a Java editor favorite. To navigate to this setting, open the Preferences and type "favorites".
org.springframework.test.web.client.response.MockRestResponseCreatorsStatic factory methods for obtaining a ResponseCreator instance.
Eclipse users: consider adding this class as a Java editor favorite. To navigate, open the Preferences and type "favorites".
org.springframework.test.web.client.MockRestServiceServer
Main entry point for client-side REST testing
. Used for tests that involve direct or indirect use of the RestTemplate. Provides a way to set up expected requests that will be performed through the
RestTemplate
as well as mock responses to send back thus removing the need for an actual server.
Below is an example that assumes static imports from
MockRestRequestMatchers
,
MockRestResponseCreators
, and
ExpectedCount
:
RestTemplate restTemplate = new RestTemplate() MockRestServiceServer server = MockRestServiceServer.bindTo(restTemplate).build(); server.expect(manyTimes(), requestTo("/hotels/42")).andExpect(method(HttpMethod.GET)) .andRespond(withSuccess("{ \"id\" : \"42\", \"name\" : \"Holiday Inn\"}", MediaType.APPLICATION_JSON)); Hotel hotel = restTemplate.getForObject("/hotels/{id}", Hotel.class, 42); // Use the hotel instance... // Verify all expectations met server.verify();
Note that as an alternative to the above you can also set the MockMvcClientHttpRequestFactory on a
RestTemplate
which allows executing requests against an instance of org.springframework.test.web.servlet.MockMvc.
Contract that frameworks or applications can use to pre-package a set of customizations to a WebTestClient.MockServerSpec and expose that as a shortcut.
An implementation of this interface can be plugged in via
WebTestClient.MockServerSpec#apply
where instances are likely obtained via static methods, e.g.:
import static org.example.ExampleSetup.securitySetup; // ... WebTestClient.bindToController(new TestController()) .apply(securitySetup("foo","bar")) .build();
org.springframework.mock.web.server.MockServerWebExchange
Variant of DefaultServerWebExchange for use in tests with MockServerHttpRequest and MockServerHttpResponse.
See static factory methods to create an instance.
org.springframework.mock.web.MockServletContextMock implementation of the javax.servlet.ServletContext interface.
As of Spring 5.0, this set of mocks is designed on a Servlet 4.0 baseline.
Compatible with Servlet 3.1 but can be configured to expose a specific version through
#setMajorVersion
/
#setMinorVersion
; default is 3.1. Note that Servlet 3.1 support is limited: servlet, filter and listener registration methods are not supported; neither is JSP configuration. We generally do not recommend to unit test your ServletContainerInitializers and WebApplicationInitializers which is where those registration methods would be used.
For setting up a full
WebApplicationContext
in a test environment, you can use
AnnotationConfigWebApplicationContext
,
XmlWebApplicationContext
, or
GenericWebApplicationContext
, passing in a corresponding
MockServletContext
instance. Consider configuring your
MockServletContext
with a
FileSystemResourceLoader
in order to interpret resource paths as relative filesystem locations.
A collection of assertions intended to simplify testing scenarios dealing with Spring Web MVC org.springframework.web.servlet.ModelAndView objects.
Intended for use with JUnit 4 and TestNG. All
assert*()
methods throw AssertionErrors.
Exception to be thrown on error conditions that should forward to a specific view with a specific model.
Can be thrown at any time during handler processing. This includes any template methods of pre-built controllers. For example, a form controller might abort to a specific error page if certain parameters do not allow to proceed with the normal workflow.
org.springframework.web.servlet.mvc.method.annotation.ModelAndViewMethodReturnValueHandlerHandles return values of type ModelAndView copying view and model information to the ModelAndViewContainer.
If the return value is
null
, the
ModelAndViewContainer#setRequestHandled(boolean)
flag is set to
true
to indicate the request was handled directly.
A ModelAndView return type has a set purpose. Therefore this handler should be configured ahead of handlers that support any return value type annotated with
@ModelAttribute
or
@ResponseBody
to ensure they don't take over.
SPI for resolving custom return values from a specific handler method. Typically implemented to detect special return types, resolving well-known result values for them.
A typical implementation could look like as follows:
public class MyModelAndViewResolver implements ModelAndViewResolver { public ModelAndView resolveModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, NativeWebRequest webRequest) { if (returnValue instanceof MySpecialRetVal.class)) { return new MySpecialRetVal(returnValue); } return UNRESOLVED; } }
org.springframework.web.servlet.mvc.method.annotation.ModelAndViewResolverMethodReturnValueHandler
This return value handler is intended to be ordered after all others as it attempts to handle _any_ return value type (i.e. returns
true
for all return types).
The return value is handled either with a ModelAndViewResolver or otherwise by regarding it as a model attribute if it is a non-simple type. If neither of these succeeds (essentially simple type other than String), UnsupportedOperationException is raised.
Note:
This class is primarily needed to support ModelAndViewResolver, which unfortunately cannot be properly adapted to the HandlerMethodReturnValueHandler contract since the
HandlerMethodReturnValueHandler#supportsReturnType
method cannot be implemented. Hence
ModelAndViewResolver
s are limited to always being invoked at the end after all other return value handlers have been given a chance. It is recommended to re-implement a
ModelAndViewResolver
as
HandlerMethodReturnValueHandler
, which also provides better access to the return type and method information.
Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view. Supported for controller classes with RequestMapping methods.
Can be used to expose command objects to a web view, using specific attribute names, through annotating corresponding parameters of an RequestMapping method.
Can also be used to expose reference data to a web view through annotating accessor methods in a controller class with RequestMapping methods. Such accessor methods are allowed to have any arguments that RequestMapping methods support, returning the model attribute value to expose.
Note however that reference data and all other model content is not available to web views when request processing results in an
Exception
since the exception could be raised at any time making the content of the model unreliable. For this reason ExceptionHandler methods do not provide access to a Model argument.
Resolve
@ModelAttribute
annotated method arguments.
Model attributes are sourced from the model, or created using a default constructor and then added to the model. Once created the attribute is populated via data binding to the request (form data, query params). Validation also may be applied if the argument is annotated with
@javax.validation.Valid
or Spring's own
@org.springframework.validation.annotation.Validated
.
When this handler is created with
useDefaultResolution=true
any non-simple type argument and return value is regarded as a model attribute with or without the presence of an
@ModelAttribute
.
Resolve
@ModelAttribute
annotated method arguments and handle return values from
@ModelAttribute
annotated methods.
Model attributes are obtained from the model or created with a default constructor (and then added to the model). Once created the attribute is populated via data binding to Servlet request parameters. Validation may be applied if the argument is annotated with
@javax.validation.Valid
. or Spring's own
@org.springframework.validation.annotation.Validated
.
When this handler is created with
annotationNotRequired=true
any non-simple type argument and return value is regarded as a model attribute with or without the presence of an
@ModelAttribute
.
Assist with initialization of the Model before controller method invocation and with updates to it after the invocation.
On initialization the model is populated with attributes temporarily stored in the session and through the invocation of
@ModelAttribute
methods.
On update model attributes are synchronized with the session and also BindingResult attributes are added if missing.
org.springframework.web.method.annotation.ModelMethodProcessorResolves Model arguments and handles Model return values.
A Model return type has a set purpose. Therefore this handler should be configured ahead of handlers that support any return value type annotated with
@ModelAttribute
or
@ResponseBody
to ensure they don't take over.
Factory for assertions on the model.
An instance of this class is typically accessed via
MockMvcResultMatchers#model
.
SimpUserRegistry
that looks up users in a "local" user registry as well as a set of "remote" user registries. The local registry is provided as a constructor argument while remote registries are updated via broadcasts handled by UserRegistryMessageHandler which in turn notifies this registry when updates are received.
A mutable builder for multipart form bodies. For example:
MultipartBodyBuilder builder = new MultipartBodyBuilder(); builder.part("form field", "form value"); Resource image = new ClassPathResource("image.jpg"); builder.part("image", image).header("Baz", "Qux"); MultiValueMap> multipartBody = builder.build(); // use multipartBody with RestTemplate or WebClient
org.springframework.web.multipart.support.MultipartFilter
Servlet Filter that resolves multipart requests via a MultipartResolver. in the root web application context.
Looks up the MultipartResolver in Spring's root web application context. Supports a "multipartResolverBeanName" filter init-param in
web.xml
; the default bean name is "filterMultipartResolver".
If no MultipartResolver bean is found, this filter falls back to a default MultipartResolver: StandardServletMultipartResolver for Servlet 3.0, based on a multipart-config section in
web.xml
. Note however that at present the Servlet specification only defines how to enable multipart configuration on a Servlet and as a result multipart request processing is likely not possible in a Filter unless the Servlet container provides a workaround such as Tomcat's "allowCasualMultipartParsing" property.
MultipartResolver lookup is customizable: Override this filter's
lookupMultipartResolver
method to use a custom MultipartResolver instance, for example if not using a Spring web application context. Note that the lookup method should not create a new MultipartResolver instance for each call but rather return a reference to a pre-built instance.
Note: This filter is an alternative to using DispatcherServlet's MultipartResolver support, for example for web applications with custom web views which do not use Spring's web MVC, or for custom filters applied before a Spring MVC DispatcherServlet (e.g. org.springframework.web.filter.HiddenHttpMethodFilter). In any case, this filter should not be combined with servlet-specific multipart resolution.
org.springframework.http.codec.multipart.MultipartHttpMessageReader
HttpMessageReader
for reading
"multipart/form-data"
requests into a
MultiValueMap<String, Part>
.
Note that this reader depends on access to an
HttpMessageReader<Part>
for the actual parsing of multipart content. The purpose of this reader is to collect the parts into a map.
HttpMessageWriter for writing a
MultiValueMap<String, ?>
as multipart form data, i.e.
"multipart/form-data"
, to the body of a request.
The serialization of individual parts is delegated to other writers. By default only String and Resource parts are supported but you can configure others through a constructor argument.
This writer can be configured with a FormHttpMessageWriter to delegate to. It is the preferred way of supporting both form data and multipart data (as opposed to registering each writer separately) so that when the MediaType is not specified and generics are not present on the target element type, we can inspect the values in the actual map and decide whether to write plain form data (String values only) or otherwise.
org.springframework.jdbc.support.incrementer.MySQLMaxValueIncrementerDataFieldMaxValueIncrementer that increments the maximum value of a given MySQL table with the equivalent of an auto-increment column. Note: If you use this class, your MySQL key column should NOT be auto-increment, as the sequence table does the job.
The sequence is kept in a table; there should be one sequence table per table that needs an auto-generated key. The storage engine used by the sequence table can be MYISAM or INNODB since the sequences are allocated using a separate connection without being affected by any other transactions that might be in progress.
Example:
create table tab (id int unsigned not null primary key, text varchar(100)); create table tab_sequence (value int not null); insert into tab_sequence values(0);
If "cacheSize" is set, the intermediate values are served without querying the database. If the server or your application is stopped or crashes or a transaction is rolled back, the unused values will never be served. The maximum hole size in numbering is consequently the value of cacheSize.
It is possible to avoid acquiring a new connection for the incrementer by setting the "useNewConnection" property to false. In this case you MUST use a non-transactional storage engine like MYISAM when defining the incrementer table.
org.springframework.beans.factory.NamedBeanCounterpart of BeanNameAware. Returns the bean name of an object.
This interface can be introduced to avoid a brittle dependence on bean name in objects used with Spring IoC and Spring AOP.
org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperationsInterface specifying a basic set of JDBC operations allowing the use of named parameters rather than the traditional '?' placeholders.
This is an alternative to the classic org.springframework.jdbc.core.JdbcOperations interface, implemented by NamedParameterJdbcTemplate. This interface is not often used directly, but provides a useful option to enhance testability, as it can easily be mocked or stubbed.
org.springframework.jdbc.core.namedparam.NamedParameterUtilsHelper methods for named parameter parsing.
Only intended for internal use within Spring's JDBC framework.
org.springframework.core.NestedCheckedException
Handy class for wrapping checked
Exceptions
with a root cause.
This class is
abstract
to force the programmer to extend the class.
getMessage
will include nested exception information;
printStackTrace
and other like methods will delegate to the wrapped exception, if any.
The similarity between this class and the NestedRuntimeException class is unavoidable, as Java forces these two classes to have different superclasses (ah, the inflexibility of concrete inheritance!).
org.springframework.core.NestedExceptionUtilsHelper class for implementing exception classes which are capable of holding nested exceptions. Necessary because we can't share a base class among different exception types.
Mainly for use within the framework.
org.springframework.core.NestedIOExceptionSubclass of IOException that properly handles a root cause, exposing the root cause just like NestedChecked/RuntimeException does.
Proper root cause handling has not been added to standard IOException before Java 6, which is why we need to do it ourselves for Java 5 compatibility purposes.
The similarity between this class and the NestedChecked/RuntimeException class is unavoidable, as this class needs to derive from IOException.
The
<nestedPath>
tag supports and assists with nested beans or bean properties in the model. Exports a "nestedPath" variable of type String in request scope, visible to the current page and also included pages, if any.
The BindTag will auto-detect the current nested path and automatically prepend it to its own path to form a complete path to the bean or bean property.
This tag will also prepend any existing nested path that is currently set. Thus, you can nest multiple nested-path tags.
Attribute Summary Attribute Required? Runtime Expression? Description path true true Set the path that this tag should apply. E.g. 'customer' to allow bind paths like 'address.street' rather than 'customer.address.street'. org.springframework.http.client.Netty4ClientHttpRequestFactoryorg.springframework.http.client.ClientHttpRequestFactory implementation that uses Netty 4 to create requests.
Allows to use a pre-configured EventLoopGroup instance: useful for sharing across multiple clients.
Note that this implementation consistently closes the HTTP connection on each request.
org.springframework.cache.support.NoOpCacheA no operation Cache implementation suitable for disabling caching.
Will simply accept any items into the cache not actually storing them.
org.springframework.cache.support.NoOpCacheManagerA basic, no operation CacheManager implementation suitable for disabling caching, typically used for backing cache declarations without an actual backing store.
Will simply accept any items into the cache not actually storing them.
org.springframework.lang.NonNull
A common Spring annotation to declare that annotated elements cannot be
null
. Leverages JSR 305 meta-annotations to indicate nullability in Java to common tools with JSR 305 support and used by Kotlin to infer nullability of Spring API.
Should be used at parameter, return value, and field level. Method overrides should repeat parent
@NonNull
annotations unless they behave differently.
Use
@NonNullApi
(scope = parameters + return values) and/or
@NonNullFields
(scope = fields) to set the default behavior to non-nullable in order to avoid annotating your whole codebase with
@NonNull
.
A common Spring annotation to declare that parameters and return values are to be considered as non-nullable by default for a given package.
Leverages JSR-305 meta-annotations to indicate nullability in Java to common tools with JSR-305 support and used by Kotlin to infer nullability of Spring API.
Should be used at package level in association with Nullable annotations at parameter and return value level.
org.springframework.lang.NonNullFieldsA common Spring annotation to declare that fields are to be considered as non-nullable by default for a given package.
Leverages JSR-305 meta-annotations to indicate nullability in Java to common tools with JSR-305 support and used by Kotlin to infer nullability of Spring API.
Should be used at package level in association with Nullable annotations at field level.
org.springframework.jca.cci.connection.NotSupportedRecordFactoryImplementation of the CCI RecordFactory interface that always throws NotSupportedException.
Useful as a placeholder for a RecordFactory argument (for example as defined by the RecordCreator callback), in particular when the connector's
ConnectionFactory.getRecordFactory()
implementation happens to throw NotSupportedException early rather than throwing the exception from RecordFactory's methods.
Helper class that aggregates a javax.management.NotificationListener, a javax.management.NotificationFilter, and an arbitrary handback object.
Also provides support for associating the encapsulated javax.management.NotificationListener with any number of MBeans from which it wishes to receive javax.management.Notification via the
mappedObjectNames
property.
Note: This class supports Spring bean names as
"mappedObjectNames"
as well, as alternative to specifying JMX object names. Note that only beans exported by the same MBeanExporter are supported for such bean names.
Interface to be implemented by any Spring-managed resource that is to be registered with an javax.management.MBeanServer and wishes to send JMX javax.management.Notification.
Provides Spring-created managed resources with a NotificationPublisher as soon as they are registered with the javax.management.MBeanServer.
NOTE: This interface only applies to simple Spring-managed beans which happen to get exported through Spring's org.springframework.jmx.export.MBeanExporter. It does not apply to any non-exported beans; neither does it apply to standard MBeans exported by Spring. For standard JMX MBeans, consider implementing the javax.management.modelmbean.ModelMBeanNotificationBroadcaster interface (or implementing a full javax.management.modelmbean.ModelMBean).
org.springframework.beans.factory.parsing.NullSourceExtractor
Simple implementation of SourceExtractor that returns
null
as the source metadata.
This is the default implementation and prevents too much metadata from being held in memory during normal (non-tooled) runtime usage.
org.springframework.beans.NullValueInNestedPathExceptionException thrown when navigation of a valid nested property path encounters a NullPointerException.
For example, navigating "spouse.age" could fail because the spouse property of the target object has a null value.
org.springframework.format.annotation.NumberFormatDeclares that a field or method parameter should be formatted as a number.
Supports formatting by style or custom pattern string. Can be applied to any JDK
java.lang.Number
type.
For style-based formatting, set the
#style
attribute to be the desired Style. For custom formatting, set the
#pattern
attribute to be the number pattern, such as
#, ###.##
.
Each attribute is mutually exclusive, so only set one attribute per annotation instance (the one most convenient one for your formatting needs). When the
#pattern
attribute is specified, it takes precedence over the
#style
attribute. When no annotation attributes are specified, the default format applied is style-based for either number of currency, depending on the annotated field or method parameter type.
Encapsulates an object error, that is, a global reason for rejecting an object.
See the DefaultMessageCodesResolver javadoc for details on how a message code list is built for an
ObjectError
.
A org.springframework.beans.factory.FactoryBean implementation that returns a value which is an org.springframework.beans.factory.ObjectFactory that in turn returns a bean sourced from a org.springframework.beans.factory.BeanFactory.
As such, this may be used to avoid having a client object directly calling
org.springframework.beans.factory.BeanFactory#getBean(String)
to get a (typically prototype) bean from a org.springframework.beans.factory.BeanFactory, which would be a violation of the inversion of control principle. Instead, with the use of this class, the client object can be fed an org.springframework.beans.factory.ObjectFactory instance as a property which directly returns only the one target bean (again, which is typically a prototype bean).
A sample config in an XML-based org.springframework.beans.factory.BeanFactory might look as follows:
<beans> <!-- Prototype bean since we have state --> <bean id="myService" class="a.b.c.MyService" scope="prototype"/> <bean id="myServiceFactory" class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean"> <property name="targetBeanName"><idref local="myService"/></property> </bean> <bean id="clientBean" class="a.b.c.MyClientBean"> <property name="myServiceFactory" ref="myServiceFactory"/> </bean> </beans>
The attendant
MyClientBean
class implementation might look something like this:
package a.b.c; import org.springframework.beans.factory.ObjectFactory; public class MyClientBean { private ObjectFactory<MyService> myServiceFactory; public void setMyServiceFactory(ObjectFactory<MyService> myServiceFactory) { this.myServiceFactory = myServiceFactory; } public void someBusinessMethod() { // get a 'fresh', brand new MyService instance MyService service = this.myServiceFactory.getObject(); // use the service object to effect the business logic... } }
An alternate approach to this application of an object creational pattern would be to use the ServiceLocatorFactoryBean to source (prototype) beans. The ServiceLocatorFactoryBean approach has the advantage of the fact that one doesn't have to depend on any Spring-specific interface such as org.springframework.beans.factory.ObjectFactory, but has the disadvantage of requiring runtime class generation. Please do consult the ServiceLocatorFactoryBean for a fuller discussion of this issue.
org.springframework.http.converter.ObjectToStringHttpMessageConverter
An
HttpMessageConverter
that uses StringHttpMessageConverter for reading and writing content and a ConversionService for converting the String content to and from the target object type.
By default, this converter supports the media type
text/plain
only. This can be overridden through the
supportedMediaTypes
property.
A usage example:
<bean class="org.springframework.http.converter.ObjectToStringHttpMessageConverter"> <constructor-arg> <bean class="org.springframework.context.support.ConversionServiceFactoryBean"/> </constructor-arg> </bean>
org.springframework.expression.spel.ast.OpMinus
The minus operator supports:
It can be used as a unary operator for numbers. The standard promotions are performed when the operand types vary (double-int=double). For other options it defers to the registered overloader.
Implements the
multiply
operator.
Conversions and promotions are handled as defined in
Section 5.6.2 of the Java Language Specification
, with the addiction of
BigDecimal
/
BigInteger
management:
If any of the operands is of a reference type, unboxing conversion (Section 5.1.8) is performed. Then: If either operand is of type
BigDecimal
, the other is converted to
BigDecimal
. If either operand is of type double, the other is converted to double. Otherwise, if either operand is of type float, the other is converted to float. If either operand is of type
BigInteger
, the other is converted to
BigInteger
. Otherwise, if either operand is of type long, the other is converted to long. Otherwise, both operands are converted to type int.
Servlet Filter that binds a JPA EntityManager to the thread for the entire processing of the request. Intended for the "Open EntityManager in View" pattern, i.e. to allow for lazy loading in web views despite the original transactions already being completed.
This filter makes JPA EntityManagers available via the current thread, which will be autodetected by transaction managers. It is suitable for service layer transactions via org.springframework.orm.jpa.JpaTransactionManager or org.springframework.transaction.jta.JtaTransactionManager as well as for non-transactional read-only execution.
Looks up the EntityManagerFactory in Spring's root web application context. Supports an "entityManagerFactoryBeanName" filter init-param in
web.xml
; the default bean name is "entityManagerFactory". As an alternative, the "persistenceUnitName" init-param allows for retrieval by logical unit name (as specified in
persistence.xml
).
Spring web request interceptor that binds a JPA EntityManager to the thread for the entire processing of the request. Intended for the "Open EntityManager in View" pattern, i.e. to allow for lazy loading in web views despite the original transactions already being completed.
This interceptor makes JPA EntityManagers available via the current thread, which will be autodetected by transaction managers. It is suitable for service layer transactions via org.springframework.orm.jpa.JpaTransactionManager or org.springframework.transaction.jta.JtaTransactionManager as well as for non-transactional read-only execution.
In contrast to OpenEntityManagerInViewFilter, this interceptor is set up in a Spring application context and can thus take advantage of bean wiring.
org.springframework.orm.hibernate5.support.OpenSessionInViewFilterServlet Filter that binds a Hibernate Session to the thread for the entire processing of the request. Intended for the "Open Session in View" pattern, i.e. to allow for lazy loading in web views despite the original transactions already being completed.
This filter makes Hibernate Sessions available via the current thread, which will be autodetected by transaction managers. It is suitable for service layer transactions via org.springframework.orm.hibernate5.HibernateTransactionManager as well as for non-transactional execution (if configured appropriately).
NOTE
: This filter will by default
not
flush the Hibernate Session, with the flush mode set to
FlushMode.NEVER
. It assumes to be used in combination with service layer transactions that care for the flushing: The active transaction manager will temporarily change the flush mode to
FlushMode.AUTO
during a read-write transaction, with the flush mode reset to
FlushMode.NEVER
at the end of each transaction.
WARNING: Applying this filter to existing logic can cause issues that have not appeared before, through the use of a single Hibernate Session for the processing of an entire request. In particular, the reassociation of persistent objects with a Hibernate Session has to occur at the very beginning of request processing, to avoid clashes with already loaded instances of the same objects.
Looks up the SessionFactory in Spring's root web application context. Supports a "sessionFactoryBeanName" filter init-param in
web.xml
; the default bean name is "sessionFactory".
Spring web request interceptor that binds a Hibernate
Session
to the thread for the entire processing of the request.
This class is a concrete expression of the "Open Session in View" pattern, which is a pattern that allows for the lazy loading of associations in web views despite the original transactions already being completed.
This interceptor makes Hibernate Sessions available via the current thread, which will be autodetected by transaction managers. It is suitable for service layer transactions via org.springframework.orm.hibernate5.HibernateTransactionManager as well as for non-transactional execution (if configured appropriately).
In contrast to OpenSessionInViewFilter, this interceptor is configured in a Spring application context and can thus take advantage of bean wiring.
WARNING:
Applying this interceptor to existing logic can cause issues that have not appeared before, through the use of a single Hibernate
Session
for the processing of an entire request. In particular, the reassociation of persistent objects with a Hibernate
Session
has to occur at the very beginning of request processing, to avoid clashes with already loaded instances of the same objects.
Simple AOP Alliance MethodInterceptor implementation that binds a new Hibernate Session for each method invocation, if none bound before.
This is a simple Hibernate Session scoping interceptor along the lines of OpenSessionInViewInterceptor, just for use with AOP setup instead of MVC setup. It opens a new Session with flush mode "MANUAL" since the Session is only meant for reading, except when participating in a transaction.
org.springframework.expression.spel.ast.OperatorBetweenRepresents the between operator. The left operand to between must be a single value and the right operand must be a list - this operator returns true if the left operand is between (using the registered comparator) the two elements in the list. The definition of between being inclusive follows the SQL BETWEEN definition.
org.springframework.web.servlet.tags.form.OptionTag
The
<option>
tag renders a single HTML 'option'. Sets 'selected' as appropriate based on bound value.
Must be used nested inside a SelectTag.
Provides full support for databinding by marking an '
option
' as 'selected' if the
value
matches the value bound to the out SelectTag.
The
value
property is required and corresponds to the '
value
' attribute of the rendered '
option
'.
An optional
label
property can be specified, the value of which corresponds to inner text of the rendered '
option
' tag. If no
label
is specified then the
value
property will be used when rendering the inner text.
cssClass
false
HTML Optional Attribute
cssErrorClass
false
HTML Optional Attribute. Used when the bound field has errors.
cssStyle
false
HTML Optional Attribute
false
HTML Standard Attribute
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
label
false
HTML Optional Attribute
false
HTML Standard Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
value
HTML Optional Attribute
org.springframework.validation.beanvalidation.OptionalValidatorFactoryBeanLocalValidatorFactoryBean subclass that simply turns org.springframework.validation.Validator calls into no-ops in case of no Bean Validation provider being available.
This is the actual class used by Spring's MVC configuration namespace, in case of the
javax.validation
API being present but no explicit Validator having been configured.
The
<options>
tag renders a list of HTML 'option' tags. Sets 'selected' as appropriate based on bound value.
Must be used within a SelectTag.
Attribute Summary Attribute Required? Runtime Expression? DescriptioncssClass
false
HTML Optional Attribute
cssErrorClass
false
HTML Optional Attribute. Used when the bound field has errors.
cssStyle
false
HTML Optional Attribute
false
HTML Standard Attribute
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
itemLabel
false
Name of the property mapped to the inner text of the 'option' tag
items
The Collection, Map or array of objects used to generate the inner 'option' tags
itemValue
false
Name of the property mapped to 'value' attribute of the 'option' tag
false
HTML Standard Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
org.springframework.jdbc.core.metadata.OracleTableMetaDataProvider
Oracle-specific implementation of the org.springframework.jdbc.core.metadata.TableMetaDataProvider. Supports a feature for including synonyms in the metadata lookup. Also supports lookup of current schema using the
sys_context
.
Thanks to Mike Youngstrom and Bruce Campbell for submitting the original suggestion for the Oracle current schema lookup implementation.
org.springframework.core.annotation.Order
@Order
defines the sort order for an annotated component.
The
#value
is optional and represents an order value as defined in the Ordered interface. Lower values have higher priority. The default value is
Ordered.LOWEST_PRECEDENCE
, indicating lowest priority (losing to any other specified order value).
NOTE:
Since Spring 4.0, annotation-based ordering is supported for many kinds of components in Spring, even for collection injection where the order values of the target components are taken into account (either from their target class or from their
@Bean
method). While such order values may influence priorities at injection points, please be aware that they do not influence singleton startup order which is an orthogonal concern determined by dependency relationships and
@DependsOn
declarations (influencing a runtime-determined dependency graph).
Since Spring 4.1, the standard javax.annotation.Priority annotation can be used as a drop-in replacement for this annotation in ordering scenarios. Note that
Priority
may have additional semantics when a single element has to be picked (see
AnnotationAwareOrderComparator#getPriority
).
Alternatively, order values may also be determined on a per-instance basis through the Ordered interface, allowing for configuration-determined instance values instead of hard-coded values attached to a particular class.
Consult the javadoc for org.springframework.core.OrderComparator for details on the sort semantics for non-ordered objects.
org.springframework.beans.support.PagedListHolderPagedListHolder is a simple state holder for handling lists of objects, separating them into pages. Page numbering starts with 0.
This is mainly targetted at usage in web UIs. Typically, an instance will be instantiated with a list of beans, put into the session, and exported as model. The properties can all be set/get programmatically, but the most common way will be data binding, i.e. populating the bean from request parameters. The getters will mainly be used by the view.
Supports sorting the underlying list via a SortDefinition implementation, available as property "sort". By default, a MutableSortDefinition instance will be used, toggling the ascending value on setting the same property again.
The data binding names have to be called "pageSize" and "sort.ascending", as expected by BeanWrapper. Note that the names and the nesting syntax match the respective JSTL EL expressions, like "myModelAttr.pageSize" and "myModelAttr.sort.ascending".
org.springframework.web.servlet.tags.ParamTag
The
<param>
tag collects name-value parameters and passes them to a ParamAware ancestor in the tag hierarchy.
This tag must be nested under a param aware tag.
Attribute Summary Attribute Required? Runtime Expression? Description name true true The name of the parameter. value false true The value of the parameter. org.springframework.web.accept.ParameterContentNegotiationStrategyStrategy that resolves the requested content type from a query parameter. The default query parameter name is "format".
You can register static mappings between keys (i.e. the expected value of the query parameter) and MediaType's via
#addMapping(String, MediaType)
. As of 5.0 this strategy also supports dynamic lookups of keys via
org.springframework.http.MediaTypeFactory#getMediaType
.
Simple SourceExtractor implementation that just passes the candidate source metadata object through for attachment.
Using this implementation means that tools will get raw access to the underlying configuration source metadata provided by the tool.
This implementation should not be used in a production application since it is likely to keep too much metadata in memory (unnecessarily).
org.springframework.web.servlet.tags.form.PasswordInputTag
The
<password>
tag renders an HTML 'input' tag with type 'password' using the bound value.
Attribute Summary Attribute Required? Runtime Expression? Description
accesskey
false
HTML Standard Attribute
false
HTML Optional Attribute
autocomplete
false
Common Optional Attribute
cssClass
false
HTML Optional Attribute
cssErrorClass
false
HTML Optional Attribute. Used when the bound field has errors.
cssStyle
false
HTML Optional Attribute
false
HTML Standard Attribute
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
false
HTML Standard Attribute
maxlength
false
HTML Optional Attribute
onblur
false
HTML Event Attribute
onchange
false
HTML Event Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onfocus
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
onselect
false
HTML Event Attribute
Path to property for data binding
readonly
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will make the HTML element readonly.
showPassword
false
Is the password value to be shown? Defaults to false.
false
HTML Optional Attribute
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
org.springframework.web.bind.annotation.PatchMapping
Annotation for mapping HTTP
PATCH
requests onto specific handler methods.
Specifically,
@PatchMapping
is a
composed annotation
that acts as a shortcut for
@RequestMapping(method = RequestMethod.PATCH)
.
Editor for
java.nio.file.Path
, to directly populate a Path property instead of using a String property as bridge.
Based on
Paths#get(URI)
's resolution algorithm, checking registered NIO file system providers, including the default file system for "file:..." paths. Also supports Spring-style URL notation: any fully qualified standard URL and Spring's special "classpath:" pseudo-URL, as well as Spring's context-specific relative file paths. As a fallback, a path will be resolved in the file system via
Paths#get(String)
if no existing context-relative resource could be found.
A
ContentNegotiationStrategy
that resolves the file extension in the request path to a key to be used to look up a media type.
If the file extension is not found in the explicit registrations provided to the constructor, the MediaTypeFactory is used as a fallback mechanism.
org.springframework.core.io.support.PathMatchingResourcePatternResolver
A ResourcePatternResolver implementation that is able to resolve a specified resource location path into one or more matching Resources. The source path may be a simple path which has a one-to-one mapping to a target org.springframework.core.io.Resource, or alternatively may contain the special "
classpath*:
" prefix and/or internal Ant-style regular expressions (matched using Spring's org.springframework.util.AntPathMatcher utility). Both of the latter are effectively wildcards.
No Wildcards:
In the simple case, if the specified location path does not start with the
"classpath*:
" prefix, and does not contain a PathMatcher pattern, this resolver will simply return a single resource via a
getResource()
call on the underlying
ResourceLoader
. Examples are real URLs such as "
file:C:/context.xml
", pseudo-URLs such as "
classpath:/context.xml
", and simple unprefixed paths such as "
/WEB-INF/context.xml
". The latter will resolve in a fashion specific to the underlying
ResourceLoader
(e.g.
ServletContextResource
for a
WebApplicationContext
).
Ant-style Patterns:
When the path location contains an Ant-style pattern, e.g.:
/WEB-INF/*-context.xml com/mycompany/**/applicationContext.xml file:C:/some/path/*-context.xml classpath:com/mycompany/**/applicationContext.xml
the resolver follows a more complex but defined procedure to try to resolve the wildcard. It produces a
Resource
for the path up to the last non-wildcard segment and obtains a
URL
from it. If this URL is not a "
jar:
" URL or container-specific variant (e.g. "
zip:
" in WebLogic, "
wsjar
" in WebSphere", etc.), then a
java.io.File
is obtained from it, and used to resolve the wildcard by walking the filesystem. In the case of a jar URL, the resolver either gets a
java.net.JarURLConnection
from it, or manually parses the jar URL, and then traverses the contents of the jar file, to resolve the wildcards.
Implications on portability:
If the specified path is already a file URL (either explicitly, or implicitly because the base
ResourceLoader
is a filesystem one, then wildcarding is guaranteed to work in a completely portable fashion.
If the specified path is a classpath location, then the resolver must obtain the last non-wildcard path segment URL via a
Classloader.getResource()
call. Since this is just a node of the path (not the file at the end) it is actually undefined (in the ClassLoader Javadocs) exactly what sort of a URL is returned in this case. In practice, it is usually a
java.io.File
representing the directory, where the classpath resource resolves to a filesystem location, or a jar URL of some sort, where the classpath resource resolves to a jar location. Still, there is a portability concern on this operation.
If a jar URL is obtained for the last non-wildcard segment, the resolver must be able to get a
java.net.JarURLConnection
from it, or manually parse the jar URL, to be able to walk the contents of the jar, and resolve the wildcard. This will work in most environments, but will fail in others, and it is strongly recommended that the wildcard resolution of resources coming from jars be thoroughly tested in your specific environment before you rely on it.
classpath*:
Prefix:
There is special support for retrieving multiple class path resources with the same name, via the "
classpath*:
" prefix. For example, "
classpath*:META-INF/beans.xml
" will find all "beans.xml" files in the class path, be it in "classes" directories or in JAR files. This is particularly useful for autodetecting config files of the same name at the same location within each jar file. Internally, this happens via a
ClassLoader.getResources()
call, and is completely portable.
The "classpath*:" prefix can also be combined with a PathMatcher pattern in the rest of the location path, for example "classpath*:META-INF/*-beans.xml". In this case, the resolution strategy is fairly simple: a
ClassLoader.getResources()
call is used on the last non-wildcard path segment to get all the matching resources in the class loader hierarchy, and then off each resource the same PathMatcher resolution strategy described above is used for the wildcard subpath.
Other notes:
WARNING:
Note that "
classpath*:
" when combined with Ant-style patterns will only work reliably with at least one root directory before the pattern starts, unless the actual target files reside in the file system. This means that a pattern like "
classpath*:*.xml
" will
not
retrieve files from the root of jar files but rather only from the root of expanded directories. This originates from a limitation in the JDK's
ClassLoader.getResources()
method which only returns file system locations for a passed-in empty String (indicating potential roots to search). This
ResourcePatternResolver
implementation is trying to mitigate the jar root lookup limitation through URLClassLoader introspection and "java.class.path" manifest evaluation; however, without portability guarantees.
WARNING: Ant-style patterns with "classpath:" resources are not guaranteed to find matching resources if the root package to search is available in multiple class path locations. This is because a resource such as
com/mycompany/package1/service-context.xml
may be in only one location, but when a path such as
classpath:com/mycompany/**/service-context.xml
is used to try to resolve it, the resolver will work off the (first) URL returned by
getResource("com/mycompany");
. If this base package node exists in multiple classloader locations, the actual end resource may not be underneath. Therefore, preferably, use "
classpath*:
" with the same Ant-style pattern in such a case, which will search
all
class path locations that contain the root package.
org.springframework.web.reactive.resource.PathResourceResolver
A simple
ResourceResolver
that tries to find a resource under the given locations matching to the request path.
This resolver does not delegate to the
ResourceResolverChain
and is expected to be configured at the end in a chain of resolvers.
A simple
ResourceResolver
that tries to find a resource under the given locations matching to the request path.
This resolver does not delegate to the
ResourceResolverChain
and is expected to be configured at the end in a chain of resolvers.
Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods in Servlet environments.
If the method parameter is java.util.Map or org.springframework.util.MultiValueMap then the map is populated with all path variable names and values.
org.springframework.web.reactive.result.method.annotation.PathVariableMapMethodArgumentResolverResolver for Map method arguments also annotated with PathVariable where the annotation does not specify a path variable name. The resulting Map argument is a coyp of all URI template name-value pairs.
org.springframework.web.servlet.mvc.method.annotation.PathVariableMapMethodArgumentResolverResolves Map method arguments annotated with an @PathVariable where the annotation does not specify a path variable name. The created Map contains all URI template name/value pairs.
org.springframework.web.reactive.result.method.annotation.PathVariableMethodArgumentResolverResolves method arguments annotated with @PathVariable.
An @PathVariable is a named value that gets resolved from a URI template variable. It is always required and does not have a default value to fall back on. See the base class org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver for more information on how named values are processed.
If the method parameter type is Map, the name specified in the annotation is used to resolve the URI variable String value. The value is then converted to a Map via type conversion, assuming a suitable Converter.
org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolverResolves method arguments annotated with an @PathVariable.
An @PathVariable is a named value that gets resolved from a URI template variable. It is always required and does not have a default value to fall back on. See the base class org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver for more information on how named values are processed.
If the method parameter type is Map, the name specified in the annotation is used to resolve the URI variable String value. The value is then converted to a Map via type conversion, assuming a suitable Converter or PropertyEditor has been registered.
A WebDataBinder is invoked to apply type conversion to resolved path variable values that don't yet match the method parameter type.
org.springframework.messaging.handler.annotation.support.PayloadArgumentResolverA resolver to extract and convert the payload of a message using a MessageConverter. It also validates the payload using a Validator if the argument is annotated with a Validation annotation.
This HandlerMethodArgumentResolver should be ordered last as it supports all types and does not require the Payload annotation.
org.springframework.web.socket.handler.PerConnectionWebSocketHandlerA WebSocketHandler that initializes and destroys a WebSocketHandler instance for each WebSocket connection and delegates all other methods to it.
Essentially create an instance of this class once, providing the type of WebSocketHandler class to create for each connection, and then pass it to any API method that expects a WebSocketHandler.
If initializing the target WebSocketHandler type requires a Spring BeanFctory, then the
#setBeanFactory(BeanFactory)
property accordingly. Simply declaring this class as a Spring bean will do that. Otherwise, WebSocketHandler instances of the target type will be created using the default constructor.
Simple AOP Alliance
MethodInterceptor
for performance monitoring. This interceptor has no effect on the intercepted method call.
Uses a
StopWatch
for the actual performance measuring.
A trigger for periodic task execution. The period may be applied as either fixed-rate or fixed-delay, and an initial delay value may also be configured. The default initial delay is 0, and the default behavior is fixed-delay (i.e. the interval between successive executions is measured from each completion time). To measure the interval between the scheduled start time of each execution instead, set the 'fixedRate' property to
true
.
Note that the TaskScheduler interface already defines methods for scheduling tasks at fixed-rate or with fixed-delay. Both also support an optional value for the initial delay. Those methods should be used directly whenever possible. The value of this Trigger implementation is that it can be used within components that rely on the Trigger abstraction. For example, it may be convenient to allow periodic triggers, cron-based triggers, and even custom Trigger implementations to be used interchangeably.
org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessorBeanPostProcessor that processes javax.persistence.PersistenceUnit and javax.persistence.PersistenceContext annotations, for injection of the corresponding JPA resources javax.persistence.EntityManagerFactory and javax.persistence.EntityManager. Any such annotated fields or methods in any Spring-managed object will automatically be injected.
This post-processor will inject sub-interfaces of
EntityManagerFactory
and
EntityManager
if the annotated fields or methods are declared as such. The actual type will be verified early, with the exception of a shared ("transactional")
EntityManager
reference, where type mismatches might be detected as late as on the first actual invocation.
Note: In the present implementation, PersistenceAnnotationBeanPostProcessor only supports
@PersistenceUnit
and
@PersistenceContext
with the "unitName" attribute, or no attribute at all (for the default unit). If those annotations are present with the "name" attribute at the class level, they will simply be ignored, since those only serve as deployment hint (as per the Java EE specification).
This post-processor can either obtain EntityManagerFactory beans defined in the Spring application context (the default), or obtain EntityManagerFactory references from JNDI ("persistence unit references"). In the bean case, the persistence unit name will be matched against the actual deployed unit, with the bean name used as fallback unit name if no deployed name found. Typically, Spring's org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean will be used for setting up such EntityManagerFactory beans. Alternatively, such beans may also be obtained from JNDI, e.g. using the
jee:jndi-lookup
XML configuration element (with the bean name matching the requested unit name). In both cases, the post-processor definition will look as simple as this:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
In the JNDI case, specify the corresponding JNDI names in this post-processor's
"persistenceUnits" map
, typically with matching
persistence-unit-ref
entries in the Java EE deployment descriptor. By default, those names are considered as resource references (according to the Java EE resource-ref convention), located underneath the "java:comp/env/" namespace. For example:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"> <property name="persistenceUnits"> <map/gt; <entry key="unit1" value="persistence/unit1"/> <entry key="unit2" value="persistence/unit2"/> </map/gt; </property> </bean>
In this case, the specified persistence units will always be resolved in JNDI rather than as Spring-defined beans. The entire persistence unit deployment, including the weaving of persistent classes, is then up to the Java EE server. Persistence contexts (i.e. EntityManager references) will be built based on those server-provided EntityManagerFactory references, using Spring's own transaction synchronization facilities for transactional EntityManager handling (typically with Spring's
@Transactional
annotation for demarcation and org.springframework.transaction.jta.JtaTransactionManager as backend).
If you prefer the Java EE server's own EntityManager handling, specify entries in this post-processor's
"persistenceContexts" map
(or
"extendedPersistenceContexts" map
, typically with matching
persistence-context-ref
entries in the Java EE deployment descriptor. For example:
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"> <property name="persistenceContexts"> <map/gt; <entry key="unit1" value="persistence/context1"/> <entry key="unit2" value="persistence/context2"/> </map/gt; </property> </bean>
If the application only obtains EntityManager references in the first place, this is all you need to specify. If you need EntityManagerFactory references as well, specify entries for both "persistenceUnits" and "persistenceContexts", pointing to matching JNDI locations.
NOTE: In general, do not inject EXTENDED EntityManagers into STATELESS beans, i.e. do not use
@PersistenceContext
with type
EXTENDED
in Spring beans defined with scope 'singleton' (Spring's default scope).
Extended EntityManagers are
not
thread-safe, hence they must not be used in concurrently accessed beans (which Spring-managed singletons usually are).
Note: A default PersistenceAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom PersistenceAnnotationBeanPostProcessor bean definition.
org.springframework.dao.support.PersistenceExceptionTranslationInterceptorAOP Alliance MethodInterceptor that provides persistence exception translation based on a given PersistenceExceptionTranslator.
Delegates to the given PersistenceExceptionTranslator to translate a RuntimeException thrown into Spring's DataAccessException hierarchy (if appropriate). If the RuntimeException in question is declared on the target method, it is always propagated as-is (with no translation applied).
org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessorBean post-processor that automatically applies persistence exception translation to any bean marked with Spring's @org.springframework.stereotype.Repository annotation, adding a corresponding PersistenceExceptionTranslationAdvisor to the exposed proxy (either an existing AOP proxy or a newly generated proxy that implements all of the target's interfaces).
Translates native resource exceptions to Spring's org.springframework.dao.DataAccessException hierarchy. Autodetects beans that implement the org.springframework.dao.support.PersistenceExceptionTranslator interface, which are subsequently asked to translate candidate exceptions.
All of Spring's applicable resource factories (e.g. org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean) implement the
PersistenceExceptionTranslator
interface out of the box. As a consequence, all that is usually needed to enable automatic exception translation is marking all affected beans (such as Repositories or DAOs) with the
@Repository
annotation, along with defining this post-processor as a bean in the application context.
Interface that defines an abstraction for finding and managing JPA PersistenceUnitInfos. Used by org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean in order to obtain a javax.persistence.spi.PersistenceUnitInfo for building a concrete javax.persistence.EntityManagerFactory.
Obtaining a PersistenceUnitInfo instance is an exclusive process. A PersistenceUnitInfo instance is not available for further calls anymore once it has been obtained.
org.springframework.beans.factory.xml.PluggableSchemaResolverEntityResolver implementation that attempts to resolve schema URLs into local ClassPathResource using a set of mappings files.
By default, this class will look for mapping files in the classpath using the pattern:
META-INF/spring.schemas
allowing for multiple files to exist on the classpath at any one time. The format of
META-INF/spring.schemas
is a properties file where each line should be of the form
systemId=schema-location
where
schema-location
should also be a schema file in the classpath. Since systemId is commonly a URL, one must be careful to escape any ':' characters which are treated as delimiters in properties files.
The pattern for the mapping files can be overidden using the
#PluggableSchemaResolver(ClassLoader, String)
constructor
Annotation for mapping HTTP
POST
requests onto specific handler methods.
Specifically,
@PostMapping
is a
composed annotation
that acts as a shortcut for
@RequestMapping(method = RequestMethod.POST)
.
Subclass of PropertyPlaceholderConfigurer that supports JDK 1.4's Preferences API (
java.util.prefs
).
Tries to resolve placeholders as keys first in the user preferences, then in the system preferences, then in this configurer's properties. Thus, behaves like PropertyPlaceholderConfigurer if no corresponding preferences defined.
Supports custom paths for the system and user preferences trees. Also supports custom paths specified in placeholders ("myPath/myPlaceholderKey"). Uses the respective root node if not specified.
org.springframework.context.annotation.PrimaryIndicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.
This annotation is semantically equivalent to the
<bean>
element's
primary
attribute in Spring XML.
May be used on any class directly or indirectly annotated with
@Component
or on methods annotated with @Bean.
@Component public class FooService { private FooRepository fooRepository; @Autowired public FooService(FooRepository fooRepository) { this.fooRepository = fooRepository; } } @Component public class JdbcFooRepository extends FooRepository { public JdbcFooRepository(DataSource dataSource) { // ... } } @Primary @Component public class HibernateFooRepository extends FooRepository { public HibernateFooRepository(SessionFactory sessionFactory) { // ... } }
Because
HibernateFooRepository
is marked with
@Primary
, it will be injected preferentially over the jdbc-based variant assuming both are present as beans within the same Spring application context, which is often the case when component-scanning is applied liberally.
Note that using
@Primary
at the class level has no effect unless component-scanning is being used. If a
@Primary
-annotated class is declared via XML,
@Primary
annotation metadata is ignored, and
<bean primary="true|false"/>
is respected instead.
Result handler that prints MvcResult details to a given output stream — for example:
System.out
,
System.err
, a custom
java.io.PrintWriter
, etc.
An instance of this class is typically accessed via one of the
print
or
log
methods in MockMvcResultHandlers.
ParameterNameDiscoverer implementation that tries several discoverer delegates in succession. Those added first in the
addDiscoverer
method have highest priority. If one returns
null
, the next will be tried.
The default behavior is to return
null
if no discoverer matches.
Callback for sending a message to a JMS destination.
To be used with JmsTemplate's callback methods that take a ProducerCallback argument, often implemented as an anonymous inner class or as a lambda expression.
The typical implementation will perform multiple operations on the supplied JMS Session and MessageProducer.
org.springframework.context.annotation.ProfileIndicates that a component is eligible for registration when one or more specified profiles are active.
A
profile
is a named logical grouping that may be activated programmatically via
ConfigurableEnvironment#setActiveProfiles
or declaratively by setting the
spring.profiles.active
property as a JVM system property, as an environment variable, or as a Servlet context parameter in
web.xml
for web applications. Profiles may also be activated declaratively in integration tests via the
@ActiveProfiles
annotation.
The
@Profile
annotation may be used in any of the following ways:
@Component
, including Configuration classes
If a
@Configuration
class is marked with
@Profile
, all of the
@Bean
methods and Import annotations associated with that class will be bypassed unless one or more of the specified profiles are active. This is analogous to the behavior in Spring XML: if the
profile
attribute of the
beans
element is supplied e.g.,
<beans profile="p1,p2">
, the
beans
element will not be parsed unless at least profile 'p1' or 'p2' has been activated. Likewise, if a
@Component
or
@Configuration
class is marked with
@Profile({"p1", "p2"})
, that class will not be registered or processed unless at least profile 'p1' or 'p2' has been activated.
If a given profile is prefixed with the NOT operator (
!
), the annotated component will be registered if the profile is
not
active — for example, given
@Profile({"p1", "!p2"})
, registration will occur if profile 'p1' is active or if profile 'p2' is
not
active.
If the
@Profile
annotation is omitted, registration will occur regardless of which (if any) profiles are active.
NOTE:
With
@Profile
on
@Bean
methods, a special scenario may apply: In the case of overloaded
@Bean
methods of the same Java method name (analogous to constructor overloading), an
@Profile
condition needs to be consistently declared on all overloaded methods. If the conditions are inconsistent, only the condition on the first declaration among the overloaded methods will matter.
@Profile
can therefore not be used to select an overloaded method with a particular argument signature over another; resolution between all factory methods for the same bean follows Spring's constructor resolution algorithm at creation time.
Use distinct Java method names pointing to the same
bean name
if you'd like to define alternative beans with different profile conditions
; see
ProfileDatabaseConfig
in Configuration's javadoc.
When defining Spring beans via XML, the
"profile"
attribute of the
<beans>
element may be used. See the documentation in the
spring-beans
XSD (version 3.1 or greater) for details.
ProfileValueSourceConfiguration
is a class-level annotation which is used to specify what type of ProfileValueSource to use when retrieving
profile values
configured via the IfProfileValue annotation.
As of Spring Framework 4.0, this annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.beans.factory.support.PropertiesBeanDefinitionReaderBean definition reader for a simple properties format.
Provides bean definition registration methods for Map/Properties and ResourceBundle. Typically applied to a DefaultListableBeanFactory.
Example:
employee.(class)=MyClass // bean is of class MyClass employee.(abstract)=true // this bean can't be instantiated directly employee.group=Insurance // real property employee.usesDialUp=false // real property (potentially overridden) salesrep.(parent)=employee // derives from "employee" bean definition salesrep.(lazy-init)=true // lazily initialize this singleton bean salesrep.manager(ref)=tony // reference to another bean salesrep.department=Sales // real property techie.(parent)=employee // derives from "employee" bean definition techie.(scope)=prototype // bean is a prototype (not a shared instance) techie.manager(ref)=jeff // reference to another bean techie.department=Engineering // real property techie.usesDialUp=true // real property (overriding parent value) ceo.$0(ref)=secretary // inject 'secretary' bean as 0th constructor arg ceo.$1=1000000 // inject value '1000000' at 1st constructor arg
org.springframework.beans.factory.config.PropertiesFactoryBean
Allows for making a properties file from a classpath location available as Properties instance in a bean factory. Can be used to populate any bean property of type Properties via a bean reference.
Supports loading from a properties file and/or setting local properties on this FactoryBean. The created Properties instance will be merged from loaded and local values. If neither a location nor local properties are set, an exception will be thrown on initialization.
Can create a singleton or a new object on each request. Default is a singleton.
org.springframework.core.convert.Property
A description of a JavaBeans Property that allows us to avoid a dependency on
java.beans.PropertyDescriptor
. The
java.beans
package is not available in a number of environments (e.g. Android, Java ME), so this is desirable for portability of Spring's core conversion facility.
Used to build a TypeDescriptor from a property location. The built TypeDescriptor can then be used to convert from/to the property type.
org.springframework.beans.PropertyBatchUpdateExceptionCombined exception, composed of individual PropertyAccessException instances. An object of this class is created at the beginning of the binding process, and errors added to it as necessary.
The binding process continues when it encounters application-level PropertyAccessExceptions, applying those changes that can be applied and storing rejected changes in an object of this class.
org.springframework.beans.PropertyMatchesHelper class for calculating property matches, according to a configurable distance. Provide the list of potential matches and an easy way to generate an error message. Works for both java bean properties and fields.
Mainly for use within the framework and in particular the binding facility.
org.springframework.beans.factory.config.PropertyOverrideConfigurerProperty resource configurer that overrides bean property values in an application context definition. It pushes values from a properties file into bean definitions.
Configuration lines are expected to be of the following form:
beanName.property=value
Example properties file:
dataSource.driverClassName=com.mysql.jdbc.Driver dataSource.url=jdbc:mysql:mydb
In contrast to PropertyPlaceholderConfigurer, the original definition can have default values or no values at all for such bean properties. If an overriding properties file does not have an entry for a certain bean property, the default context definition is used.
Note that the context definition is not aware of being overridden; so this is not immediately obvious when looking at the XML definition file. Furthermore, note that specified override values are always literal values; they are not translated into bean references. This also applies when the original value in the XML bean definition specifies a bean reference.
In case of multiple PropertyOverrideConfigurers that define different values for the same bean property, the last one will win (due to the overriding mechanism).
Property values can be converted after reading them in, through overriding the
convertPropertyValue
method. For example, encrypted values can be detected and decrypted accordingly before processing them.
FactoryBean that evaluates a property path on a given target object.
The target object can be specified directly or via a bean name.
Usage examples:
<!-- target bean to be referenced by name --> <bean id="tb" class="org.springframework.beans.TestBean" singleton="false"> <property name="age" value="10"/> <property name="spouse"> <bean class="org.springframework.beans.TestBean"> <property name="age" value="11"/> </bean> </property> </bean> <!-- will result in 12, which is the value of property 'age' of the inner bean --> <bean id="propertyPath1" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"> <property name="targetObject"> <bean class="org.springframework.beans.TestBean"> <property name="age" value="12"/> </bean> </property> <property name="propertyPath" value="age"/> </bean> <!-- will result in 11, which is the value of property 'spouse.age' of bean 'tb' --> <bean id="propertyPath2" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"> <property name="targetBeanName" value="tb"/> <property name="propertyPath" value="spouse.age"/> </bean> <!-- will result in 10, which is the value of property 'age' of bean 'tb' --> <bean id="tb.age" class="org.springframework.beans.factory.config.PropertyPathFactoryBean"/>
If you are using Spring 2.0 and XML Schema support in your configuration file(s), you can also use the following style of configuration for property path access. (See also the appendix entitled 'XML Schema-based configuration' in the Spring reference manual for more examples.)
<!-- will result in 10, which is the value of property 'age' of bean 'tb' --> <util:property-path id="name" path="testBean.age"/>
Thanks to Matthias Ernst for the suggestion and initial prototype!
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
PlaceholderConfigurerSupport subclass that resolves ${...} placeholders against
local
properties
and/or system properties and environment variables.
As of Spring 3.1, org.springframework.context.support.PropertySourcesPlaceholderConfigurer should be used preferentially over this implementation; it is more flexible through taking advantage of the org.springframework.core.env.Environment and org.springframework.core.env.PropertySource mechanisms also made available in Spring 3.1.
PropertyPlaceholderConfigurer is still appropriate for use when:
spring-context
module is not available (i.e., one is using Spring's
BeanFactory
API as opposed to
ApplicationContext
).
"systemPropertiesMode"
and/or
"systemPropertiesModeName"
properties. Users are encouraged to move away from using these settings, and rather configure property source search order through the container's
Environment
; however, exact preservation of functionality may be maintained by continuing to use
PropertyPlaceholderConfigurer
.
Prior to Spring 3.1, the
<context:property-placeholder/>
namespace element registered an instance of
PropertyPlaceholderConfigurer
. It will still do so if using the
spring-context-3.0.xsd
definition of the namespace. That is, you can preserve registration of
PropertyPlaceholderConfigurer
through the namespace, even if using Spring 3.1; simply do not update your
xsi:schemaLocation
and continue using the 3.0 XSD.
Container annotation that aggregates several PropertySource annotations.
Can be used natively, declaring several nested PropertySource annotations. Can also be used in conjunction with Java 8's support for repeatable annotations , where PropertySource can simply be declared several times on the same type , implicitly generating this container annotation.
org.springframework.context.support.PropertySourcesPlaceholderConfigurer
Specialization of PlaceholderConfigurerSupport that resolves ${...} placeholders within bean definition property values and
@Value
annotations against the current Spring Environment and its set of PropertySources.
This class is designed as a general replacement for
PropertyPlaceholderConfigurer
in Spring 3.1 applications. It is used by default to support the
property-placeholder
element in working against the spring-context-3.1 XSD, whereas spring-context versions <= 3.0 default to
PropertyPlaceholderConfigurer
to ensure backward compatibility. See the spring-context XSD documentation for complete details.
Any local properties (e.g. those added via
#setProperties
,
#setLocations
et al.) are added as a
PropertySource
. Search precedence of local properties is based on the value of the
localOverride
property, which is by default
false
meaning that local properties are to be searched last, after all environment property sources.
See org.springframework.core.env.ConfigurableEnvironment and related javadocs for details on manipulating environment property sources.
org.springframework.beans.PropertyValueObject to hold information and value for an individual bean property. Using an object here, rather than just storing all properties in a map keyed by property name, allows for more flexibility, and the ability to handle indexed properties etc in an optimized way.
Note that the value doesn't need to be the final required type: A BeanWrapper implementation should handle any necessary conversion, as this object doesn't know anything about the objects it will be applied to.
org.springframework.beans.PropertyValuesEditorjava.beans.PropertyEditor for a PropertyValues object.
The required format is defined in the java.util.Properties documentation. Each property must be on a new line.
The present implementation relies on a org.springframework.beans.propertyeditors.PropertiesEditor underneath.
org.springframework.http.converter.protobuf.ProtobufJsonFormatHttpMessageConverter
Subclass of ProtobufHttpMessageConverter which enforces the use of Protobuf 3 and its official library
"com.google.protobuf:protobuf-java-util"
for JSON processing.
Most importantly, this class allows for custom JSON parser and printer configurations through the JsonFormat utility. If no special parser or printer configuration is given, default variants will be used instead.
Requires Protobuf 3.x and
"com.google.protobuf:protobuf-java-util"
3.x, with 3.3 or higher recommended.
org.springframework.aop.aspectj.AspectInstanceFactory backed by a BeanFactory-provided prototype, enforcing prototype semantics.
Note that this may instantiate multiple times, which probably won't give the semantics you expect. Use a LazySingletonAspectInstanceFactoryDecorator to wrap this to ensure only one new aspect comes back.
org.springframework.aop.target.PrototypeTargetSourceorg.springframework.aop.TargetSource implementation that creates a new instance of the target bean for each request, destroying each instance on release (after each request).
Obtains bean instances from its containing org.springframework.beans.factory.BeanFactory.
org.springframework.beans.factory.config.ProviderCreatingFactoryBeanA org.springframework.beans.factory.FactoryBean implementation that returns a value which is a JSR-330 javax.inject.Provider that in turn returns a bean sourced from a org.springframework.beans.factory.BeanFactory.
This is basically a JSR-330 compliant variant of Spring's good old ObjectFactoryCreatingFactoryBean. It can be used for traditional external dependency injection configuration that targets a property or constructor argument of type
javax.inject.Provider
, as an alternative to JSR-330's
@Inject
annotation-driven approach.
org.springframework.beans.factory.FactoryBean implementation that builds an AOP proxy based on beans in Spring org.springframework.beans.factory.BeanFactory.
org.aopalliance.intercept.MethodInterceptor and org.springframework.aop.Advisor are identified by a list of bean names in the current bean factory, specified through the "interceptorNames" property. The last entry in the list can be the name of a target bean or a org.springframework.aop.TargetSource; however, it is normally preferable to use the "targetName"/"target"/"targetSource" properties instead.
Global interceptors and advisors can be added at the factory level. The specified ones are expanded in an interceptor list where an "xxx*" entry is included in the list, matching the given prefix with the bean names (e.g. "global*" would match both "globalBean1" and "globalBean2", "*" all defined interceptors). The matching interceptors get applied according to their returned order value, if they implement the org.springframework.core.Ordered interface.
Creates a JDK proxy when proxy interfaces are given, and a CGLIB proxy for the actual target class if not. Note that the latter will only work if the target class does not have final methods, as a dynamic subclass will be created at runtime.
It's possible to cast a proxy obtained from this factory to Advised, or to obtain the ProxyFactoryBean reference and programmatically manipulate it. This won't work for existing prototype references, which are independent. However, it will work for prototypes subsequently obtained from the factory. Changes to interception will work immediately on singletons (including existing references). However, to change interfaces or target it's necessary to obtain a new instance from the factory. This means that singleton instances obtained from the factory do not have the same object identity. However, they do have the same interceptors and target, and changing any reference will change all objects.
org.springframework.cache.jcache.config.ProxyJCacheConfiguration
@Configuration
class that registers the Spring infrastructure beans necessary to enable proxy-based annotation-driven JSR-107 cache management.
Can safely be used alongside Spring's caching support.
org.springframework.web.bind.annotation.PutMapping
Annotation for mapping HTTP
PUT
requests onto specific handler methods.
Specifically,
@PutMapping
is a
composed annotation
that acts as a shortcut for
@RequestMapping(method = RequestMethod.PUT)
.
Represents a dot separated sequence of strings that indicate a package qualified type reference.
Example: "java.lang.String" as in the expression "new java.lang.String('hello')"
org.springframework.beans.factory.annotation.QualifierAnnotationAutowireCandidateResolverAutowireCandidateResolver implementation that matches bean definition qualifiers against Qualifier on the field or parameter to be autowired. Also supports suggested expression values through a Value annotation.
Also supports JSR-330's javax.inject.Qualifier annotation, if available.
org.springframework.scheduling.quartz.QuartzJobBeanSimple implementation of the Quartz Job interface, applying the passed-in JobDataMap and also the SchedulerContext as bean property values. This is appropriate because a new Job instance will be created for each execution. JobDataMap entries will override SchedulerContext entries with the same keys.
For example, let's assume that the JobDataMap contains a key "myParam" with value "5": The Job implementation can then expose a bean property "myParam" of type int to receive such a value, i.e. a method "setMyParam(int)". This will also work for complex types like business objects etc.
Note that the preferred way to apply dependency injection to Job instances is via a JobFactory:
that is, to specify SpringBeanJobFactory as Quartz JobFactory (typically via
SchedulerFactoryBean#setJobFactory
SchedulerFactoryBean's "jobFactory" property}). This allows to implement dependency-injected Quartz Jobs without a dependency on Spring base classes.
Exception to be thrown on a query timeout. This could have different causes depending on the database API in use but most likely thrown after the database interrupts or stops the processing of a query before it has completed.
This exception can be thrown by user code trapping the native database exception or by exception translation.
org.springframework.aop.framework.autoproxy.target.QuickTargetSourceCreatorConvenient TargetSourceCreator using bean name prefixes to create one of three well-known TargetSource types:
The
<radiobutton>
tag renders an HTML 'input' tag with type 'radio'.
Rendered elements are marked as 'checked' if the configured
value
matches the
bound value
.
A typical usage pattern will involved multiple tag instances bound to the same property but with different values.
Attribute Summary Attribute Required? Runtime Expression? Descriptionaccesskey
false
HTML Standard Attribute
cssClass
false
HTML Optional Attribute
cssErrorClass
false
HTML Optional Attribute. Used when the bound field has errors.
cssStyle
false
HTML Optional Attribute
false
HTML Standard Attribute
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
label
false
Value to be displayed as part of the tag
false
HTML Standard Attribute
onblur
false
HTML Event Attribute
onchange
false
HTML Event Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onfocus
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
Path to property for data binding
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
value
false
HTML Optional Attribute
org.springframework.web.servlet.tags.form.RadioButtonsTag
The
<radiobuttons>
tag renders multiple HTML 'input' tags with type 'radio'.
Rendered elements are marked as 'checked' if the configured
value
matches the bound value.
accesskey
false
HTML Standard Attribute
cssClass
false
HTML Optional Attribute
cssErrorClass
false
HTML Optional Attribute. Used when the bound field has errors.
cssStyle
false
HTML Optional Attribute
delimiter
false
Delimiter to use between each 'input' tag with type 'radio'. There is no delimiter by default.
false
HTML Standard Attribute
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
element
false
Specifies the HTML element that is used to enclose each 'input' tag with type 'radio'. Defaults to 'span'.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
itemLabel
false
Value to be displayed as part of the 'input' tags with type 'radio'
items
The Collection, Map or array of objects used to generate the 'input' tags with type 'radio'
itemValue
false
Name of the property mapped to 'value' attribute of the 'input' tags with type 'radio'
false
HTML Standard Attribute
onblur
false
HTML Event Attribute
onchange
false
HTML Event Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onfocus
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
Path to property for data binding
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
org.springframework.aop.RawTargetAccessMarker for AOP proxy interfaces (in particular: introduction interfaces) that explicitly intend to return the raw target object (which would normally get replaced with the proxy object when returned from a method invocation).
Note that this is a marker interface in the style of java.io.Serializable, semantically applying to a declared interface rather than to the full class of a concrete object. In other words, this marker applies to a particular interface only (typically an introduction interface that does not serve as the primary interface of an AOP proxy), and hence does not affect other interfaces that a concrete AOP proxy may implement.
org.springframework.core.ReactiveAdapterRegistry
A registry of adapters to adapt a Reactive Streams Publisher to/from various async/reactive types such as
CompletableFuture
, RxJava
Observable
, and others.
By default, depending on classpath availability, adapters are registered for Reactor, RxJava 1, RxJava 2 types, CompletableFuture, and Java 9+ Flow.Publisher.
org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategyA RequestUpgradeStrategy for use with Reactor Netty.
org.springframework.beans.propertyeditors.ReaderEditor
One-way PropertyEditor which can convert from a text String to a
java.io.Reader
, interpreting the given String as a Spring resource location (e.g. a URL String).
Supports Spring-style URL notation: any fully qualified standard URL ("file:", "http:", etc.) and Spring's special "classpath:" pseudo-URL.
Note that such readers usually do not get closed by Spring itself!
org.springframework.web.servlet.mvc.support.RedirectAttributes
A specialization of the Model interface that controllers can use to select attributes for a redirect scenario. Since the intent of adding redirect attributes is very explicit -- i.e. to be used for a redirect URL, attribute values may be formatted as Strings and stored that way to make them eligible to be appended to the query string or expanded as URI variables in
org.springframework.web.servlet.view.RedirectView
.
This interface also provides a way to add flash attributes. For a general overview of flash attributes see FlashMap. You can use RedirectAttributes to store flash attributes and they will be automatically propagated to the "output" FlashMap of the current request.
Example usage in an
@Controller
:
@RequestMapping(value = "/accounts", method = RequestMethod.POST) public String handle(Account account, BindingResult result, RedirectAttributes redirectAttrs) { if (result.hasErrors()) { return "accounts/new"; } // Save account ... redirectAttrs.addAttribute("id", account.getId()).addFlashAttribute("message", "Account created!"); return "redirect:/accounts/{id}"; }
A RedirectAttributes model is empty when the method is called and is never used unless the method returns a redirect view name or a RedirectView.
After the redirect, flash attributes are automatically added to the model of the controller that serves the target URL.
org.springframework.web.servlet.mvc.method.annotation.RedirectAttributesMethodArgumentResolverResolves method arguments of type RedirectAttributes.
This resolver must be listed ahead of org.springframework.web.method.annotation.ModelMethodProcessor and org.springframework.web.method.annotation.MapMethodProcessor, which support Map and Model arguments both of which are "super" types of
RedirectAttributes
and would also attempt to resolve a
RedirectAttributes
argument.
ReflectionTestUtils
is a collection of reflection-based utility methods for use in unit and integration testing scenarios.
There are often times when it would be beneficial to be able to set a non-
public
field, invoke a non-
public
setter method, or invoke a non-
public
configuration
or
lifecycle
callback method when testing code involving, for example:
private
or
protected
field access as opposed to
public
setter methods for properties in a domain entity.
private
or
protected
fields, setter methods, and configuration methods.
In addition, several methods in this class provide support for
static
fields — for example,
#setField(Class, String, Object)
,
#getField(Class, String)
, etc.
Simple utility class for working with the reflection API and handling reflection exceptions.
Only intended for internal use.
org.springframework.instrument.classloading.ReflectiveLoadTimeWeaverLoadTimeWeaver which uses reflection to delegate to an underlying ClassLoader with well-known transformation hooks. The underlying ClassLoader is expected to support the following weaving methods (as defined in the LoadTimeWeaver interface):
public void addTransformer(java.lang.instrument.ClassFileTransformer)
: for registering the given ClassFileTransformer on this ClassLoader
public ClassLoader getThrowawayClassLoader()
: for obtaining a throwaway class loader for this ClassLoader (optional; ReflectiveLoadTimeWeaver will fall back to a SimpleThrowawayClassLoader if that method isn't available)
Please note that the above methods must reside in a class that is publicly accessible, although the class itself does not have to be visible to the application's class loader.
The reflective nature of this LoadTimeWeaver is particularly useful when the underlying ClassLoader implementation is loaded in a different class loader itself (such as the application server's class loader which is not visible to the web application). There is no direct API dependency between this LoadTimeWeaver adapter and the underlying ClassLoader, just a 'loose' method contract.
This is the LoadTimeWeaver to use e.g. with the Resin application server version 3.1+.
org.springframework.aop.framework.ReflectiveMethodInvocationSpring's implementation of the AOP Alliance org.aopalliance.intercept.MethodInvocation interface, implementing the extended org.springframework.aop.ProxyMethodInvocation interface.
Invokes the target object using reflection. Subclasses can override the
#invokeJoinpoint()
method to change this behavior, so this is also a useful base class for more specialized MethodInvocation implementations.
It is possible to clone an invocation, to invoke
#proceed()
repeatedly (once per clone), using the
#invocableClone()
method. It is also possible to attach custom attributes to the invocation, using the
#setUserAttribute
/
#getUserAttribute
methods.
NOTE: This class is considered internal and should not be directly accessed. The sole reason for it being public is compatibility with existing framework integrations (e.g. Pitchfork). For any other purposes, use the ProxyMethodInvocation interface instead.
org.springframework.expression.spel.support.ReflectivePropertyAccessorSimple PropertyAccessor that uses reflection to access properties for reading and writing.
A property can be accessed through a public getter method (when being read) or a public setter method (when being written), and also as a public field.
org.springframework.aop.support.RegexpMethodPointcutAdvisorConvenient class for regexp method pointcuts that hold an Advice, making them an org.springframework.aop.Advisor.
Configure this class using the "pattern" and "patterns" pass-through properties. These are analogous to the pattern and patterns properties of AbstractRegexpMethodPointcut.
Can delegate to any AbstractRegexpMethodPointcut subclass. By default, JdkRegexpMethodPointcut will be used. To choose a specific one, override the
#createPointcut
method.
Overrides
HttpServletResponse#sendRedirect(String)
and handles it by setting the HTTP status and "Location" headers. This keeps the Servlet container from re-writing relative redirect URLs and instead follows the recommendation in
RFC 7231 Section 7.1.2
.
Note: While relative redirects are more efficient they may not work with reverse proxies under some configurations.
org.springframework.context.support.ReloadableResourceBundleMessageSourceSpring-specific org.springframework.context.MessageSource implementation that accesses resource bundles using specified basenames, participating in the Spring org.springframework.context.ApplicationContext's resource loading.
In contrast to the JDK-based ResourceBundleMessageSource, this class uses java.util.Properties instances as its custom data structure for messages, loading them via a org.springframework.util.PropertiesPersister strategy from Spring Resource handles. This strategy is not only capable of reloading files based on timestamp changes, but also of loading properties files with a specific character encoding. It will detect XML property files as well.
Note that the basenames set as
"basenames"
property are treated in a slightly different fashion than the "basenames" property of ResourceBundleMessageSource. It follows the basic ResourceBundle rule of not specifying file extension or language codes, but can refer to any Spring resource location (instead of being restricted to classpath resources). With a "classpath:" prefix, resources can still be loaded from the classpath, but "cacheSeconds" values other than "-1" (caching forever) might not work reliably in this case.
For a typical web application, message files could be placed in
WEB-INF
: e.g. a "WEB-INF/messages" basename would find a "WEB-INF/messages.properties", "WEB-INF/messages_en.properties" etc arrangement as well as "WEB-INF/messages.xml", "WEB-INF/messages_en.xml" etc. Note that message definitions in a
previous
resource bundle will override ones in a later bundle, due to sequential lookup.
This MessageSource can easily be used outside of an org.springframework.context.ApplicationContext: it will use a org.springframework.core.io.DefaultResourceLoader as default, simply getting overridden with the ApplicationContext's resource loader if running in a context. It does not have any other specific dependencies.
Thanks to Thomas Achleitner for providing the initial implementation of this message source!
org.springframework.remoting.support.RemoteInvocationExecutorStrategy interface for executing a RemoteInvocation on a target object.
Used by org.springframework.remoting.rmi.RmiServiceExporter (for RMI invokers) and by org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter.
org.springframework.remoting.support.RemoteInvocationTraceInterceptorAOP Alliance MethodInterceptor for tracing remote invocations. Automatically applied by RemoteExporter and its subclasses.
Logs an incoming remote call as well as the finished processing of a remote call at DEBUG level. If the processing of a remote call results in a checked exception, the exception will get logged at INFO level; if it results in an unchecked exception (or error), the exception will get logged at WARN level.
The logging of exceptions is particularly useful to save the stacktrace information on the server-side rather than just propagating the exception to the client (who might or might not log it properly).
org.springframework.remoting.support.RemoteInvocationUtilsGeneral utilities for handling remote invocations.
Mainly intended for use within the remoting framework.
org.springframework.web.reactive.result.view.Rendering
Public API for HTML rendering. Supported as a return value in Spring WebFlux controllers. Comparable to the use of
ModelAndView
as a return value in Spring MVC controllers.
Controllers typically return a String view name and rely on the "implicit" model which can also be injected into the controller method. Or controllers may return model attribute(s) and rely on a default view name being selected based on the request path.
Rendering can be used to combine a view name with model attributes, set the HTTP status or headers, and for other more advanced options around redirect scenarios.
org.springframework.test.annotation.RepeatTest annotation to indicate that a test method should be invoked repeatedly.
Note that the scope of execution to be repeated includes execution of the test method itself as well as any set up or tear down of the test fixture.
As of Spring Framework 4.0, this annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.beans.factory.support.ReplaceOverrideExtension of MethodOverride that represents an arbitrary override of a method by the IoC container.
Any non-final method can be overridden, irrespective of its parameters and return types.
org.springframework.web.bind.annotation.RequestAttributeAnnotation to bind a method parameter to a request attribute.
The main motivation is to provide convenient access to request attributes from a controller method with an optional/required check and a cast to the target method parameter type.
org.springframework.web.reactive.result.method.annotation.RequestAttributeMethodArgumentResolverResolves method arguments annotated with an @RequestAttribute.
org.springframework.web.servlet.mvc.method.annotation.RequestAttributeMethodArgumentResolverResolves method arguments annotated with an @RequestAttribute.
org.springframework.web.bind.annotation.RequestBody
Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with
@Valid
.
Supported for annotated handler methods in Servlet environments.
org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice
Allows customizing the request before its body is read and converted into an Object and also allows for processing of the resulting Object before it is passed into a controller method as an
@RequestBody
or an
HttpEntity
method argument.
Implementations of this contract may be registered directly with the
RequestMappingHandlerAdapter
or more likely annotated with
@ControllerAdvice
in which case they are auto-detected.
Resolves method arguments annotated with
@RequestBody
by reading the body of the request through a compatible
HttpMessageReader
.
An
@RequestBody
method argument is also validated if it is annotated with
@javax.validation.Valid
or org.springframework.validation.annotation.Validated. Validation failure results in an ServerWebInputException.
Servlet Filter that exposes the request to the current thread, through both org.springframework.context.i18n.LocaleContextHolder and RequestContextHolder. To be registered as filter in
web.xml
.
Alternatively, Spring's org.springframework.web.context.request.RequestContextListener and Spring's org.springframework.web.servlet.DispatcherServlet also expose the same request context to the current thread.
This filter is mainly for use with third-party servlets, e.g. the JSF FacesServlet. Within Spring's own web support, DispatcherServlet's processing is perfectly sufficient.
org.springframework.web.context.request.RequestContextListener
Servlet listener that exposes the request to the current thread, through both org.springframework.context.i18n.LocaleContextHolder and RequestContextHolder. To be registered as listener in
web.xml
.
Alternatively, Spring's org.springframework.web.filter.RequestContextFilter and Spring's org.springframework.web.servlet.DispatcherServlet also expose the same request context to the current thread. In contrast to this listener, advanced options are available there (e.g. "threadContextInheritable").
This listener is mainly for use with third-party servlets, e.g. the JSF FacesServlet. Within Spring's own web support, DispatcherServlet's processing is perfectly sufficient.
org.springframework.web.servlet.support.RequestContextUtilsUtility class for easy access to request-specific state which has been set by the org.springframework.web.servlet.DispatcherServlet.
Supports lookup of current WebApplicationContext, LocaleResolver, Locale, ThemeResolver, Theme, and MultipartResolver.
org.springframework.test.web.client.RequestExpectation
An extension of
ResponseActions
that also implements
RequestMatcher
and
ResponseCreator
While
ResponseActions
is the API for defining expectations this sub-interface is the internal SPI for matching these expectations to actual requests and for creating responses.
Event raised when a request is handled within an ApplicationContext.
Supported by Spring's own FrameworkServlet (through a specific ServletRequestHandledEvent subclass), but can also be raised by any other web component. Used, for example, by Spring's out-of-the-box PerformanceMonitorListener.
org.springframework.web.method.annotation.RequestHeaderMapMethodArgumentResolver
Resolves Map method arguments annotated with
@RequestHeader
. For individual header values annotated with
@RequestHeader
see RequestHeaderMethodArgumentResolver instead.
The created Map contains all request header name/value pairs. The method parameter type may be a MultiValueMap to receive all values for a header, not only the first one.
org.springframework.web.reactive.result.method.annotation.RequestHeaderMapMethodArgumentResolver
Resolves Map method arguments annotated with
@RequestHeader
. For individual header values annotated with
@RequestHeader
see RequestHeaderMethodArgumentResolver instead.
The created Map contains all request header name/value pairs. The method parameter type may be a MultiValueMap to receive all values for a header, not only the first one.
org.springframework.web.method.annotation.RequestHeaderMethodArgumentResolver
Resolves method arguments annotated with
@RequestHeader
except for Map arguments. See RequestHeaderMapMethodArgumentResolver for details on Map arguments annotated with
@RequestHeader
.
An
@RequestHeader
is a named value resolved from a request header. It has a required flag and a default value to fall back on when the request header does not exist.
A WebDataBinder is invoked to apply type conversion to resolved request header values that don't yet match the method parameter type.
org.springframework.web.reactive.result.method.annotation.RequestHeaderMethodArgumentResolver
Resolves method arguments annotated with
@RequestHeader
except for Map arguments. See RequestHeaderMapMethodArgumentResolver for details on Map arguments annotated with
@RequestHeader
.
An
@RequestHeader
is a named value resolved from a request header. It has a required flag and a default value to fall back on when the request header does not exist.
A ConversionService is invoked to apply type conversion to resolved request header values that don't yet match the method parameter type.
org.springframework.web.reactive.result.method.RequestMappingInfoEncapsulates the following request mapping conditions:
RequestCondition
(optional, custom request condition)
A RequestCondition that consists of the following other conditions:
RequestCondition
(optional, custom request condition)
A org.springframework.web.servlet.handler.HandlerMethodMappingNamingStrategy for
RequestMappingInfo
-based handler method mappings. If the
RequestMappingInfo
name attribute is set, its value is used. Otherwise the name is based on the capital letters of the class name, followed by "#" as a separator, and the method name. For example "TC#getFoo" for a class named TestController with method getFoo.
Annotation which indicates that a method parameter should be bound to a web request parameter.
Supported for annotated handler methods in Servlet and Portlet environments.
If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map assuming an appropriate conversion strategy is available.
If the method parameter is java.util.Map or org.springframework.util.MultiValueMap and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.
org.springframework.web.method.annotation.RequestParamMapMethodArgumentResolverResolves Map method arguments annotated with an @RequestParam where the annotation does not specify a request parameter name. See RequestParamMethodArgumentResolver for resolving Map method arguments with a request parameter name.
The created Map contains all request parameter name/value pairs. If the method parameter type is MultiValueMap instead, the created map contains all request parameters and all there values for cases where request parameters have multiple values.
org.springframework.web.reactive.result.method.annotation.RequestParamMapMethodArgumentResolverResolver for Map method arguments annotated with RequestParam where the annotation does not specify a request parameter name. See RequestParamMethodArgumentResolver for resolving Map method arguments with a request parameter name.
The created Map contains all request parameter name-value pairs. If the method parameter type is MultiValueMap instead, the created map contains all request parameters and all there values for cases where request parameters have multiple values.
org.springframework.web.method.annotation.RequestParamMethodArgumentResolver
Resolves method arguments annotated with @RequestParam, arguments of type MultipartFile in conjunction with Spring's MultipartResolver abstraction, and arguments of type
javax.servlet.http.Part
in conjunction with Servlet 3.0 multipart requests. This resolver can also be created in default resolution mode in which simple types (int, long, etc.) not annotated with RequestParam are also treated as request parameters with the parameter name derived from the argument name.
If the method parameter type is Map, the name specified in the annotation is used to resolve the request parameter String value. The value is then converted to a Map via type conversion assuming a suitable Converter or PropertyEditor has been registered. Or if a request parameter name is not specified the RequestParamMapMethodArgumentResolver is used instead to provide access to all request parameters in the form of a map.
A WebDataBinder is invoked to apply type conversion to resolved request header values that don't yet match the method parameter type.
org.springframework.web.reactive.result.method.annotation.RequestParamMethodArgumentResolverResolver for method arguments annotated with @RequestParam from URI query string parameters.
This resolver can also be created in default resolution mode in which simple types (int, long, etc.) not annotated with @RequestParam are also treated as request parameters with the parameter name derived from the argument name.
If the method parameter type is Map, the name specified in the annotation is used to resolve the request parameter String value. The value is then converted to a Map via type conversion assuming a suitable Converter has been registered. Or if a request parameter name is not specified the RequestParamMapMethodArgumentResolver is used instead to provide access to all request parameters in the form of a map.
org.springframework.web.bind.annotation.RequestPartAnnotation that can be used to associate the part of a "multipart/form-data" request with a method argument.
Supported method argument types include MultipartFile in conjunction with Spring's MultipartResolver abstraction,
javax.servlet.http.Part
in conjunction with Servlet 3.0 multipart requests, or otherwise for any other method argument, the content of the part is passed through an HttpMessageConverter taking into consideration the 'Content-Type' header of the request part. This is analogous to what @RequestBody does to resolve an argument based on the content of a non-multipart regular request.
Note that @RequestParam annotation can also be used to associate the part of a "multipart/form-data" request with a method argument supporting the same method argument types. The main difference is that when the method argument is not a String, @RequestParam relies on type conversion via a registered Converter or PropertyEditor while @RequestPart relies on HttpMessageConverters taking into consideration the 'Content-Type' header of the request part. @RequestParam is likely to be used with name-value form fields while @RequestPart is likely to be used with parts containing more complex content (e.g. JSON, XML).
org.springframework.web.reactive.result.method.annotation.RequestPartMethodArgumentResolver
Resolver for
@RequestPart
arguments where the named part is decoded much like an
@RequestBody
argument but based on the content of an individual part instead. The arguments may be wrapped with a reactive type for a single value (e.g. Reactor
Mono
, RxJava
Single
).
This resolver also supports arguments of type Part which may be wrapped with are reactive type for a single or multiple values.
org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolverResolves the following method arguments:
@RequestPart
javax.servlet.http.Part
in conjunction with Servlet 3.0 multipart requests
When a parameter is annotated with
@RequestPart
, the content of the part is passed through an HttpMessageConverter to resolve the method argument with the 'Content-Type' of the request part in mind. This is analogous to what @RequestBody does to resolve an argument based on the content of a regular request.
When a parameter is not annotated or the name of the part is not specified, it is derived from the name of the method argument.
Automatic validation may be applied if the argument is annotated with
@javax.validation.Valid
. In case of validation failure, a MethodArgumentNotValidException is raised and a 400 response status code returned if org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver is configured.
Extension point for applications or 3rd party libraries that wish to further initialize a MockHttpServletRequest instance after it has been built by MockHttpServletRequestBuilder or its subclass MockMultipartHttpServletRequestBuilder.
Implementations of this interface can be provided to
MockHttpServletRequestBuilder#with(RequestPostProcessor)
at the time when a request is about to be constructed.
Resolves method arguments annotated with
@RequestBody
and handles return values from methods annotated with
@ResponseBody
by reading and writing to the body of the request or response with an HttpMessageConverter.
An
@RequestBody
method argument is also validated if it is annotated with
@javax.validation.Valid
. In case of validation failure, MethodArgumentNotValidException is raised and results in an HTTP 400 response status code if DefaultHandlerExceptionResolver is configured.
Factory for assertions on the request.
An instance of this class is typically accessed via
MockMvcResultMatchers#request
.
Request-backed org.springframework.beans.factory.config.Scope implementation.
Relies on a thread-bound RequestAttributes instance, which can be exported through RequestContextListener, org.springframework.web.filter.RequestContextFilter or org.springframework.web.servlet.DispatcherServlet.
org.springframework.web.context.annotation.RequestScope
@RequestScope
is a specialization of Scope for a component whose lifecycle is bound to the current web request.
Specifically,
@RequestScope
is a
composed annotation
that acts as a shortcut for
@Scope("request")
with the default
#proxyMode
set to
TARGET_CLASS
.
@RequestScope
may be used as a meta-annotation to create custom composed annotations.
Marks a method (typically a JavaBean setter method) as being 'required': that is, the setter method must be configured to be dependency-injected with a value.
Please do consult the javadoc for the RequiredAnnotationBeanPostProcessor class (which, by default, checks for the presence of this annotation).
org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessororg.springframework.beans.factory.config.BeanPostProcessor implementation that enforces required JavaBean properties to have been configured. Required bean properties are detected through a Java 5 annotation: by default, Spring's Required annotation.
The motivation for the existence of this BeanPostProcessor is to allow developers to annotate the setter properties of their own classes with an arbitrary JDK 1.5 annotation to indicate that the container must check for the configuration of a dependency injected value. This neatly pushes responsibility for such checking onto the container (where it arguably belongs), and obviates the need ( in part ) for a developer to code a method that simply checks that all required properties have actually been set.
Please note that an 'init' method may still need to implemented (and may still be desirable), because all that this class does is enforce that a 'required' property has actually been configured with a value. It does
not
check anything else... In particular, it does not check that a configured value is not
null
.
Note: A default RequiredAnnotationBeanPostProcessor will be registered by the "context:annotation-config" and "context:component-scan" XML tags. Remove or turn off the default annotation configuration there if you intend to specify a custom RequiredAnnotationBeanPostProcessor bean definition.
org.springframework.util.ResizableByteArrayOutputStreamAn extension of java.io.ByteArrayOutputStream that:
org.springframework.util.ResizableByteArrayOutputStream#grow(int)
and
org.springframework.util.ResizableByteArrayOutputStream#resize(int)
methods to get more control over the size of the internal buffer
As of 4.2, this class has been superseded by FastByteArrayOutputStream for Spring's internal use where no assignability to ByteArrayOutputStream is needed (since FastByteArrayOutputStream is more efficient with buffer resize management but doesn't extend the standard ByteArrayOutputStream).
org.springframework.core.ResolvableTypeProviderAny object can implement this interface to provide its actual ResolvableType.
Such information is very useful when figuring out if the instance matches a generic signature as Java does not convey the signature at runtime.
Users of this interface should be careful in complex hierarchy scenarios, especially when the generic type signature of the class changes in sub-classes. It is always possible to return
null
to fallback on a default behavior.
org.springframework.beans.factory.FactoryBean that bootstraps the specified JCA 1.7 javax.resource.spi.ResourceAdapter, starting it with a local javax.resource.spi.BootstrapContext and exposing it for bean references. It will also stop the ResourceAdapter on context shutdown. This corresponds to 'non-managed' bootstrap in a local environment, according to the JCA 1.7 specification.
This is essentially an adapter for bean-style bootstrapping of a JCA ResourceAdapter, allowing the BootstrapContext or its elements (such as the JCA WorkManager) to be specified through bean properties.
org.springframework.beans.propertyeditors.ResourceBundleEditorjava.beans.PropertyEditor implementation for standard JDK java.util.ResourceBundle.
Only supports conversion from a String, but not to a String. Find below some examples of using this class in a (properly configured) Spring container using XML-based metadata:
<bean id="errorDialog" class="..."> <!-- the 'messages' property is of type java.util.ResourceBundle. the 'DialogMessages.properties' file exists at the root of the CLASSPATH --> <property name="messages" value="DialogMessages"/> </bean>
<bean id="errorDialog" class="..."> <!-- the 'DialogMessages.properties' file exists in the 'com/messages' package --> <property name="messages" value="com/messages/DialogMessages"/> </bean>
A 'properly configured' Spring org.springframework.context.ApplicationContext might contain a org.springframework.beans.factory.config.CustomEditorConfigurer definition such that the conversion can be effected transparently:
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="java.util.ResourceBundle"> <bean class="org.springframework.beans.propertyeditors.ResourceBundleEditor"/> </entry> </map> </property> </bean>
Please note that this java.beans.PropertyEditor is not registered by default with any of the Spring infrastructure.
Thanks to David Leal Valmana for the suggestion and initial prototype.
org.springframework.context.support.ResourceBundleMessageSourceorg.springframework.context.MessageSource implementation that accesses resource bundles using specified basenames. This class relies on the underlying JDK's java.util.ResourceBundle implementation, in combination with the JDK's standard message parsing provided by java.text.MessageFormat.
This MessageSource caches both the accessed ResourceBundle instances and the generated MessageFormats for each message. It also implements rendering of no-arg messages without MessageFormat, as supported by the AbstractMessageSource base class. The caching provided by this MessageSource is significantly faster than the built-in caching of the
java.util.ResourceBundle
class.
The basenames follow java.util.ResourceBundle conventions: essentially, a fully-qualified classpath location. If it doesn't contain a package qualifier (such as
org.mypackage
), it will be resolved from the classpath root. Note that the JDK's standard ResourceBundle treats dots as package separators: This means that "test.theme" is effectively equivalent to "test/theme".
A org.springframework.web.servlet.ViewResolver implementation that uses bean definitions in a ResourceBundle, specified by the bundle basename.
The bundle is typically defined in a properties file, located in the classpath. The default bundle basename is "views".
This
ViewResolver
supports localized view definitions, using the default support of java.util.PropertyResourceBundle. For example, the basename "views" will be resolved as class path resources "views_de_AT.properties", "views_de.properties", "views.properties" - for a given Locale "de_AT".
Note: This
ViewResolver
implements the Ordered interface in order to allow for flexible participation in
ViewResolver
chaining. For example, some special views could be defined via this
ViewResolver
(giving it 0 as "order" value), while all remaining views could be resolved by a UrlBasedViewResolver.
PropertyEditorRegistrar implementation that populates a given org.springframework.beans.PropertyEditorRegistry (typically a org.springframework.beans.BeanWrapper used for bean creation within an org.springframework.context.ApplicationContext) with resource editors. Used by org.springframework.context.support.AbstractApplicationContext.
org.springframework.beans.factory.xml.ResourceEntityResolverEntityResolver implementation that tries to resolve entity references through a org.springframework.core.io.ResourceLoader (usually, relative to the resource base of an ApplicationContext), if applicable. Extends DelegatingEntityResolver to also provide DTD and XSD lookup.
Allows to use standard XML entities to include XML snippets into an application context definition, for example to split a large XML file into various modules. The include paths can be relative to the application context's resource base as usual, instead of relative to the JVM working directory (the XML parser's default).
Note: In addition to relative paths, every URL that specifies a file in the current system root, i.e. the JVM working directory, will be interpreted relative to the application context too.
org.springframework.http.converter.ResourceHttpMessageConverterImplementation of HttpMessageConverter that can read/write Resource and supports byte range requests.
By default, this converter can read all media types. The MediaTypeFactory is used to determine the
Content-Type
of written resources.
Utility class for determining whether a given URL is a resource location that can be loaded via a ResourcePatternResolver.
Callers will usually assume that a location is a relative path if the
#isUrl(String)
method returns
false
.
Subclass of PropertiesPropertySource that loads a Properties object from a given org.springframework.core.io.Resource or resource location such as
"classpath:/com/myco/foo.properties"
or
"file:/path/to/file.xml"
.
Both traditional and XML-based properties file formats are supported; however, in order for XML processing to take effect, the underlying
Resource
's
getFilename()
method must return a non-
null
value that ends in
".xml"
.
Annotation that indicates a method return value should be bound to the web response body. Supported for annotated handler methods in Servlet environments.
As of version 4.0 this annotation can also be added on the type level in which case it is inherited and does not need to be added on the method level.
org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitterA controller method return value type for asynchronous request processing where one or more objects are written to the response.
While org.springframework.web.context.request.async.DeferredResult is used to produce a single result, a
ResponseBodyEmitter
can be used to send multiple objects where each object is written with a compatible org.springframework.http.converter.HttpMessageConverter.
Supported as a return type on its own as well as within a org.springframework.http.ResponseEntity.
@RequestMapping(value="/stream", method=RequestMethod.GET) public ResponseBodyEmitter handle() { ResponseBodyEmitter emitter = new ResponseBodyEmitter(); // Pass the emitter to another component... return emitter; } // in another thread emitter.send(foo1); // and again emitter.send(foo2); // and done emitter.complete();
org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitterReturnValueHandler
Handler for return values of type ResponseBodyEmitter and sub-classes such as SseEmitter including the same types wrapped with ResponseEntity.
As of 5.0 also supports reactive return value types for any reactive library with registered adapters in ReactiveAdapterRegistry.
org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
A convenient base class for ControllerAdvice classes that wish to provide centralized exception handling across all
@RequestMapping
methods through
@ExceptionHandler
methods.
This base class provides an
@ExceptionHandler
method for handling internal Spring MVC exceptions. This method returns a
ResponseEntity
for writing to the response with a HttpMessageConverter, in contrast to org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver which returns a org.springframework.web.servlet.ModelAndView.
If there is no need to write error content to the response body, or when using view resolution (e.g., via
ContentNegotiatingViewResolver
), then
DefaultHandlerExceptionResolver
is good enough.
Note that in order for an
@ControllerAdvice
sub-class to be detected, ExceptionHandlerExceptionResolver must be configured.
Marks a method or exception class with the status
#code
and
#reason
that should be returned.
The status code is applied to the HTTP response when the handler method is invoked and overrides status information set by other means, like
ResponseEntity
or
"redirect:"
.
Warning
: when using this annotation on an exception class, or when setting the
reason
attribute of this annotation, the
HttpServletResponse.sendError
method will be used.
With
HttpServletResponse.sendError
, the response is considered complete and should not be written to any further. Furthermore, the Servlet container will typically write an HTML error page therefore making the use of a
reason
unsuitable for REST APIs. For such cases it is preferable to use a org.springframework.http.ResponseEntity as a return type and avoid the use of
@ResponseStatus
altogether.
Note that a controller class may also be annotated with
@ResponseStatus
and is then inherited by all
@RequestMapping
methods.
A org.springframework.web.servlet.HandlerExceptionResolver that uses the ResponseStatus annotation to map exceptions to HTTP status codes.
This exception resolver is enabled by default in the org.springframework.web.servlet.DispatcherServlet and the MVC Java config and the MVC namespace.
As of 4.2 this resolver also looks recursively for
@ResponseStatus
present on cause exceptions, and as of 4.2.2 this resolver supports attribute overrides for
@ResponseStatus
in custom composed annotations.
As of 5.0 this resolver also supports ResponseStatusException.
org.springframework.web.bind.annotation.RestControllerA convenience annotation that is itself annotated with Controller and ResponseBody.
Types that carry this annotation are treated as controllers where RequestMapping methods assume ResponseBody semantics by default.
NOTE:
@RestController
is processed if an appropriate
HandlerMapping
-
HandlerAdapter
pair is configured such as the
RequestMappingHandlerMapping
-
RequestMappingHandlerAdapter
pair which are the default in the MVC Java config and the MVC namespace.
A convenience annotation that is itself annotated with ControllerAdvice and ResponseBody.
Types that carry this annotation are treated as controller advice where ExceptionHandler methods assume ResponseBody semantics by default.
NOTE:
@RestControllerAdvice
is processed if an appropriate
HandlerMapping
-
HandlerAdapter
pair is configured such as the
RequestMappingHandlerMapping
-
RequestMappingHandlerAdapter
pair which are the default in the MVC Java config and the MVC namespace.
Allows applying actions, such as expectations, on the result of an executed request.
See static factory methods in org.springframework.test.web.servlet.result.MockMvcResultMatchers and org.springframework.test.web.servlet.result.MockMvcResultHandlers.
org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSetThe default implementation of Spring's SqlRowSet interface, wrapping a java.sql.ResultSet, catching any SQLExceptions and translating them to a corresponding Spring InvalidResultSetAccessException.
The passed-in ResultSet should already be disconnected if the SqlRowSet is supposed to be usable in a disconnected fashion. This means that you will usually pass in a
javax.sql.rowset.CachedRowSet
, which implements the ResultSet interface.
Note: Since JDBC 4.0, it has been clarified that any methods using a String to identify the column should be using the column label. The column label is assigned using the ALIAS keyword in the SQL query string. When the query doesn't use an ALIAS, the default label is the column name. Most JDBC ResultSet implementations follow this new pattern but there are exceptions such as the
com.sun.rowset.CachedRowSetImpl
class which only uses the column name, ignoring any column labels. As of Spring 3.0.5, ResultSetWrappingSqlRowSet will translate column labels to the correct column index to provide better support for the
com.sun.rowset.CachedRowSetImpl
which is the default implementation used by org.springframework.jdbc.core.JdbcTemplate when working with RowSets.
Note: This class implements the
java.io.Serializable
marker interface through the SqlRowSet interface, but is only actually serializable if the disconnected ResultSet/RowSet contained in it is serializable. Most CachedRowSet implementations are actually serializable, so this should usually work out.
The default implementation of Spring's SqlRowSetMetaData interface, wrapping a java.sql.ResultSetMetaData instance, catching any SQLExceptions and translating them to a corresponding Spring InvalidResultSetAccessException.
Used by ResultSetWrappingSqlRowSet.
org.springframework.remoting.rmi.RmiClientInterceptorUtilsFactored-out methods for performing invocations within an RMI client. Can handle both RMI and non-RMI service interfaces working on an RMI stub.
Note: This is an SPI class, not intended to be used by applications.
org.springframework.remoting.rmi.RmiProxyFactoryBeanFactoryBean for RMI proxies, supporting both conventional RMI services and RMI invokers. Exposes the proxied service for use as a bean reference, using the specified service interface. Proxies will throw Spring's unchecked RemoteAccessException on remote invocation failure instead of RMI's RemoteException.
The service URL must be a valid RMI URL like "rmi://localhost:1099/myservice". RMI invokers work at the RmiInvocationHandler level, using the same invoker stub for any service. Service interfaces do not have to extend
java.rmi.Remote
or throw
java.rmi.RemoteException
. Of course, in and out parameters have to be serializable.
With conventional RMI services, this proxy factory is typically used with the RMI service interface. Alternatively, this factory can also proxy a remote RMI service with a matching non-RMI business interface, i.e. an interface that mirrors the RMI service methods but does not declare RemoteExceptions. In the latter case, RemoteExceptions thrown by the RMI stub will automatically get converted to Spring's unchecked RemoteAccessException.
The major advantage of RMI, compared to Hessian, is serialization. Effectively, any serializable Java object can be transported without hassle. Hessian has its own (de-)serialization mechanisms, but is HTTP-based and thus much easier to setup than RMI. Alternatively, consider Spring's HTTP invoker to combine Java serialization with HTTP-based transport.
org.springframework.remoting.rmi.RmiRegistryFactoryBeanFactoryBean that locates a java.rmi.registry.Registry and exposes it for bean references. Can also create a local RMI registry on the fly if none exists already.
Can be used to set up and pass around the actual Registry object to applications objects that need to work with RMI. One example for such an object that needs to work with RMI is Spring's RmiServiceExporter, which either works with a passed-in Registry reference or falls back to the registry as specified by its local properties and defaults.
Also useful to enforce creation of a local RMI registry at a given port, for example for a JMX connector. If used in conjunction with org.springframework.jmx.support.ConnectorServerFactoryBean, it is recommended to mark the connector definition (ConnectorServerFactoryBean) as "depends-on" the registry definition (RmiRegistryFactoryBean), to guarantee starting up the registry first.
Note: The implementation of this class mirrors the corresponding logic in RmiServiceExporter, and also offers the same customization hooks. RmiServiceExporter implements its own registry lookup as a convenience: It is very common to simply rely on the registry defaults.
org.springframework.test.annotation.Rollback
@Rollback
is a test annotation that is used to indicate whether a
test-managed transaction
should be
rolled back
after the test method has completed.
Consult the class-level Javadoc for org.springframework.test.context.transaction.TransactionalTestExecutionListener for an explanation of test-managed transactions .
When declared as a class-level annotation,
@Rollback
defines the default rollback semantics for all test methods within the test class hierarchy. When declared as a method-level annotation,
@Rollback
defines rollback semantics for the specific test method, potentially overriding class-level default commit or rollback semantics.
As of Spring Framework 4.2,
@Commit
can be used as direct replacement for
@Rollback(false)
.
Warning
: Declaring
@Commit
and
@Rollback
on the same test method or on the same test class is unsupported and may lead to unpredictable results.
This annotation may be used as a meta-annotation to create custom composed annotations . Consult the source code for Commit for a concrete example.
org.springframework.jdbc.core.RowCountCallbackHandlerImplementation of RowCallbackHandler. Convenient superclass for callback handlers. An instance can only be used once.
We can either use this on its own (for example, in a test case, to ensure that our result sets have valid dimensions), or use it as a superclass for callback handlers that actually do something, and will benefit from the dimension information it provides.
A usage example with JdbcTemplate:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object RowCountCallbackHandler countCallback = new RowCountCallbackHandler(); // not reusable jdbcTemplate.query("select * from user", countCallback); int rowCount = countCallback.getRowCount();
org.springframework.jdbc.core.RowMapperResultSetExtractor
Adapter implementation of the ResultSetExtractor interface that delegates to a RowMapper which is supposed to create an object for each row. Each object is added to the results List of this ResultSetExtractor.
Useful for the typical case of one object per row in the database table. The number of entries in the results list will match the number of rows.
Note that a RowMapper object is typically stateless and thus reusable; just the RowMapperResultSetExtractor adapter is stateful.
A usage example with JdbcTemplate:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object RowMapper rowMapper = new UserRowMapper(); // reusable object List allUsers = (List) jdbcTemplate.query( "select * from user", new RowMapperResultSetExtractor(rowMapper, 10)); User user = (User) jdbcTemplate.queryForObject( "select * from user where id=?", new Object[] {id}, new RowMapperResultSetExtractor(rowMapper, 1));
Alternatively, consider subclassing MappingSqlQuery from the
jdbc.object
package: Instead of working with separate JdbcTemplate and RowMapper objects, you can have executable query objects (containing row-mapping logic) there.
Implementation of org.springframework.http.converter.HttpMessageConverter that can read and write RSS feeds. Specifically, this converter can handle Channel objects from the ROME project.
>
NOTE: As of Spring 4.1, this is based on the
com.rometools
variant of ROME, version 1.5. Please upgrade your build dependency.
By default, this converter reads and writes the media type (
application/rss+xml
). This can be overridden through the
supportedMediaTypes
property.
RunAfterTestClassCallbacks
is a custom JUnit Statement which allows the
Spring TestContext Framework
to be plugged into the JUnit execution chain by calling
afterTestClass()
on the supplied TestContextManager.
NOTE: This class requires JUnit 4.9 or higher.
org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks
RunAfterTestExecutionCallbacks
is a custom JUnit Statement which allows the
Spring TestContext Framework
to be plugged into the JUnit 4 execution chain by calling
afterTestExecution()
on the supplied TestContextManager.
NOTE: This class requires JUnit 4.9 or higher.
org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks
RunAfterTestMethodCallbacks
is a custom JUnit Statement which allows the
Spring TestContext Framework
to be plugged into the JUnit execution chain by calling
afterTestMethod()
on the supplied TestContextManager.
NOTE: This class requires JUnit 4.9 or higher.
org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslatorImplementation of SQLExceptionTranslator that analyzes vendor-specific error codes. More precise than an implementation based on SQL state, but heavily vendor-specific.
This class applies the following matching rules:
SQLException
subclass hierarchy, we will use SQLExceptionSubclassTranslator by default, which in turns falls back to Spring's own SQL state translation when not encountering specific subclasses.
The configuration file named "sql-error-codes.xml" is by default read from this package. It can be overridden through a file of the same name in the root of the class path (e.g. in the "/WEB-INF/classes" directory), as long as the Spring JDBC package is loaded from the same ClassLoader.
org.springframework.jdbc.support.SQLExceptionSubclassTranslatorSQLExceptionTranslator implementation which analyzes the specific java.sql.SQLException subclass thrown by the JDBC driver.
Falls back to a standard SQLStateSQLExceptionTranslator if the JDBC driver does not actually expose JDBC 4 compliant
SQLException
subclasses.
Strategy interface for translating between SQLException and Spring's data access strategy-agnostic DataAccessException hierarchy.
Implementations can be generic (for example, using
SQLState
codes for JDBC) or wholly proprietary (for example, using Oracle error codes) for greater precision.
SQLExceptionTranslator implementation that analyzes the SQL state in the SQLException based on the first two digits (the SQL state "class"). Detects standard SQL state values and well-known vendor-specific SQL states.
Not able to diagnose all problems, but is portable between databases and does not require special initialization (no database vendor detection, etc.). For more precise translation, consider SQLErrorCodeSQLExceptionTranslator.
org.springframework.jdbc.SQLWarningExceptionException thrown when we're not ignoring java.sql.SQLWarning.
If a SQLWarning is reported, the operation completed, so we will need to explicitly roll it back if we're not happy when looking at the warning. We might choose to ignore (and log) the warning, or to wrap and throw it in the shape of this SQLWarningException instead.
org.springframework.context.annotation.ScannedGenericBeanDefinitionExtension of the org.springframework.beans.factory.support.GenericBeanDefinition class, based on an ASM ClassReader, with support for annotation metadata exposed through the AnnotatedBeanDefinition interface.
This class does
not
load the bean
Class
early. It rather retrieves all relevant metadata from the ".class" file itself, parsed with the ASM ClassReader. It is functionally equivalent to
AnnotatedGenericBeanDefinition#AnnotatedGenericBeanDefinition(AnnotationMetadata)
but distinguishes by type beans that have been
scanned
vs those that have been otherwise registered or detected by other means.
org.springframework.beans.factory.FactoryBean that sets up a java.util.concurrent.ScheduledExecutorService (by default: a java.util.concurrent.ScheduledThreadPoolExecutor) and exposes it for bean references.
Allows for registration of ScheduledExecutorTask, automatically starting the ScheduledExecutorService on initialization and cancelling it on destruction of the context. In scenarios that only require static registration of tasks at startup, there is no need to access the ScheduledExecutorService instance itself in application code at all;
ScheduledExecutorFactoryBean
is then just being used for lifecycle integration.
For an alternative, you may set up a ScheduledThreadPoolExecutor instance directly using constructor injection, or use a factory method definition that points to the java.util.concurrent.Executors class.
This is strongly recommended in particular for common
@Bean
methods in configuration classes, where this
FactoryBean
variant would force you to return the
FactoryBean
type instead of
ScheduledExecutorService
.
Note that java.util.concurrent.ScheduledExecutorService uses a Runnable instance that is shared between repeated executions, in contrast to Quartz which instantiates a new Job for each execution.
WARNING:
Runnable submitted via a native java.util.concurrent.ScheduledExecutorService are removed from the execution schedule once they throw an exception. If you would prefer to continue execution after such an exception, switch this FactoryBean's
"continueScheduledExecutionAfterException"
property to "true".
JavaBean that describes a scheduled executor task, consisting of the Runnable and a delay plus period. The period needs to be specified; there is no point in a default for it.
The java.util.concurrent.ScheduledExecutorService does not offer more sophisticated scheduling options such as cron expressions. Consider using ThreadPoolTaskScheduler for such needs.
Note that the java.util.concurrent.ScheduledExecutorService mechanism uses a Runnable instance that is shared between repeated executions, in contrast to Quartz which creates a new Job instance for each execution.
org.springframework.scheduling.commonj.ScheduledTimerListenerJavaBean that describes a scheduled TimerListener, consisting of the TimerListener itself (or a Runnable to create a TimerListener for) and a delay plus period. Period needs to be specified; there is no point in a default for it.
The CommonJ TimerManager does not offer more sophisticated scheduling options such as cron expressions. Consider using Quartz for such advanced needs.
Note that the TimerManager uses a TimerListener instance that is shared between repeated executions, in contrast to Quartz which instantiates a new Job for each execution.
org.springframework.scheduling.quartz.SchedulerAccessorBeanSpring bean-style class for accessing a Quartz Scheduler, i.e. for registering jobs, triggers and listeners on a given org.quartz.Scheduler instance.
Compatible with Quartz 2.1.4 and higher, as of Spring 4.1.
org.springframework.scheduling.annotation.SchedulesContainer annotation that aggregates several Scheduled annotations.
Can be used natively, declaring several nested Scheduled annotations. Can also be used in conjunction with Java 8's support for repeatable annotations, where Scheduled can simply be declared several times on the same method, implicitly generating this container annotation.
This annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.scheduling.SchedulingAwareRunnableExtension of the Runnable interface, adding special callbacks for long-running operations.
This interface closely corresponds to the CommonJ Work interface, but is kept separate to avoid a required CommonJ dependency.
Scheduling-capable TaskExecutors are encouraged to check a submitted Runnable, detecting whether this interface is implemented and reacting as appropriately as they are able to.
org.springframework.scheduling.annotation.SchedulingConfiguration
@Configuration
class that registers a ScheduledAnnotationBeanPostProcessor bean capable of processing Spring's @Scheduled annotation.
This configuration class is automatically imported when using the EnableScheduling annotation. See
@EnableScheduling
's javadoc for complete usage details.
Optional interface to be implemented by @ classes annotated with @EnableScheduling. Typically used for setting a specific org.springframework.scheduling.TaskScheduler bean to be used when executing scheduled tasks or for registering scheduled tasks in a
programmatic
fashion as opposed to the
declarative
approach of using the @Scheduled annotation. For example, this may be necessary when implementing -based tasks, which are not supported by the
@Scheduled
annotation.
See @EnableScheduling for detailed usage examples.
org.springframework.context.annotation.Scope
When used as a type-level annotation in conjunction with org.springframework.stereotype.Component,
@Scope
indicates the name of a scope to use for instances of the annotated type.
When used as a method-level annotation in conjunction with Bean,
@Scope
indicates the name of a scope to use for the instance returned from the method.
In this context,
scope
means the lifecycle of an instance, such as
singleton
,
prototype
, and so forth. Scopes provided out of the box in Spring may be referred to using the
SCOPE_*
constants available in the ConfigurableBeanFactory and
WebApplicationContext
interfaces.
To register additional custom scopes, see org.springframework.beans.factory.config.CustomScopeConfigurer.
org.springframework.aop.scope.ScopedObjectAn AOP introduction interface for scoped objects.
Objects created from the ScopedProxyFactoryBean can be cast to this interface, enabling access to the raw target object and programmatic removal of the target object.
org.springframework.aop.scope.ScopedProxyFactoryBeanConvenient proxy factory bean for scoped objects.
Proxies created using this factory bean are thread-safe singletons and may be injected into shared objects, with transparent scoping behavior.
Proxies returned by this class implement the ScopedObject interface. This presently allows for removing the corresponding object from the scope, seamlessly creating a new instance in the scope on next access.
Please note that the proxies created by this factory are class-based proxies by default. This can be customized through switching the "proxyTargetClass" property to "false".
org.springframework.scripting.support.ScriptFactoryPostProcessororg.springframework.beans.factory.config.BeanPostProcessor that handles org.springframework.scripting.ScriptFactory definitions, replacing each factory with the actual scripted Java object generated by it.
This is similar to the org.springframework.beans.factory.FactoryBean mechanism, but is specifically tailored for scripts and not built into Spring's core container itself but rather implemented as an extension.
NOTE: The most important characteristic of this post-processor is that constructor arguments are applied to the org.springframework.scripting.ScriptFactory instance while bean property values are applied to the generated scripted object. Typically, constructor arguments include a script source locator and potentially script interfaces, while bean property values include references and config values to inject into the scripted object itself.
The following ScriptFactoryPostProcessor will automatically be applied to the two org.springframework.scripting.ScriptFactory definitions below. At runtime, the actual scripted objects will be exposed for "bshMessenger" and "groovyMessenger", rather than the org.springframework.scripting.ScriptFactory instances. Both of those are supposed to be castable to the example's
Messenger
interfaces here.
<bean class="org.springframework.scripting.support.ScriptFactoryPostProcessor"/> <bean id="bshMessenger" class="org.springframework.scripting.bsh.BshScriptFactory"> <constructor-arg value="classpath:mypackage/Messenger.bsh"/> <constructor-arg value="mypackage.Messenger"/> <property name="message" value="Hello World!"/> </bean> <bean id="groovyMessenger" class="org.springframework.scripting.groovy.GroovyScriptFactory"> <constructor-arg value="classpath:mypackage/Messenger.groovy"/> <property name="message" value="Hello World!"/> </bean>
NOTE:
Please note that the above excerpt from a Spring XML bean definition file uses just the <bean/>-style syntax (in an effort to illustrate using the ScriptFactoryPostProcessor itself). In reality, you would never create a <bean/> definition for a ScriptFactoryPostProcessor explicitly; rather you would import the tags from the
'lang'
namespace and simply create scripted beans using the tags in that namespace... as part of doing so, a ScriptFactoryPostProcessor will implicitly be created for you.
The Spring reference documentation contains numerous examples of using tags in the
'lang'
namespace; by way of an example, find below a Groovy-backed bean defined using the
'lang:groovy'
tag.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:lang="http://www.springframework.org/schema/lang"> <!-- this is the bean definition for the Groovy-backed Messenger implementation --> <lang:groovy id="messenger" script-source="classpath:Messenger.groovy"> <lang:property name="message" value="I Can Do The Frug" /> </lang:groovy> <!-- an otherwise normal bean that will be injected by the Groovy-backed Messenger --> <bean id="bookingService" class="x.y.DefaultBookingService"> <property name="messenger" ref="messenger" /> </bean> </beans>
org.springframework.web.reactive.result.view.script.ScriptTemplateView
An AbstractUrlBasedView subclass designed to run any template library based on a JSR-223 script engine.
If not set, each property is auto-detected by looking up a single ScriptTemplateConfig bean in the web application context and using it to obtain the configured properties.
The Nashorn JavaScript engine requires Java 8+ and may require setting the
sharedEngine
property to
false
in order to run properly. See
ScriptTemplateConfigurer#setSharedEngine(Boolean)
for more details.
An AbstractUrlBasedView subclass designed to run any template library based on a JSR-223 script engine.
If not set, each property is auto-detected by looking up a single ScriptTemplateConfig bean in the web application context and using it to obtain the configured properties.
The Nashorn JavaScript engine requires Java 8+ and may require setting the
sharedEngine
property to
false
in order to run properly. See
ScriptTemplateConfigurer#setSharedEngine(Boolean)
for more details.
Convenience subclass of UrlBasedViewResolver that supports ScriptTemplateView and custom subclasses of it.
The view class for all views created by this resolver can be specified via the
#setViewClass(Class)
property.
Note: When chaining ViewResolvers this resolver will check for the existence of the specified template resources and only return a non-null View object if a template is actually found.
org.springframework.web.servlet.view.script.ScriptTemplateViewResolverConvenience subclass of UrlBasedViewResolver that supports ScriptTemplateView and custom subclasses of it.
The view class for all views created by this resolver can be specified via the
#setViewClass(Class)
property.
Note: When chaining ViewResolvers this resolver will check for the existence of the specified template resources and only return a non-null View object if a template is actually found.
org.springframework.expression.spel.ast.SelectionRepresents selection over a map or collection. For example: {1,2,3,4,5,6,7,8,9,10}.?{#isEven(#this) == 'y'} returns [2, 4, 6, 8, 10]
Basically a subset of the input data is returned based on the evaluation of the expression supplied as selection criteria.
org.springframework.jmx.export.naming.SelfNaming
Interface that allows infrastructure components to provide their own
ObjectName
s to the
MBeanExporter
.
Note: This interface is mainly intended for internal usage.
org.springframework.messaging.simp.annotation.support.SendToMethodReturnValueHandlerA HandlerMethodReturnValueHandler for sending to destinations specified in a SendTo or SendToUser method-level annotations.
The value returned from the method is converted, and turned to a Message and sent through the provided MessageChannel. The message is then enriched with the session id of the input message as well as the destination from the annotation(s). If multiple destinations are specified, a copy of the message is sent to each destination.
org.springframework.messaging.simp.annotation.SendToUser
Annotation that indicates that the return value of a message-handling method should be sent as a org.springframework.messaging.Message to the specified destination(s) prepended with
"/user/{username}"
where the user name is extracted from the headers of the input message being handled.
The annotation may also be placed at class-level in which case all methods in the class where the annotation applies will inherit it.
org.springframework.web.socket.server.standard.ServerEndpointExporter
Detects beans of type javax.websocket.server.ServerEndpointConfig and registers with the standard Java WebSocket runtime. Also detects beans annotated with ServerEndpoint and registers them as well. Although not required, it is likely annotated endpoints should have their
configurator
property set to SpringConfigurator.
When this class is used, by declaring it in Spring configuration, it should be possible to turn off a Servlet container's scan for WebSocket endpoints. This can be done with the help of the
<absolute-ordering>
element in
web.xml
.
Resolves ServerWebExchange-related method argument values of the following types:
For the
WebSession
see WebSessionArgumentResolver and for the
Principal
see PrincipalArgumentResolver.
A convenient base class for classes that need to wrap another ServerWebExchange. Pre-implements all methods by delegating to the wrapped instance.
Note:
if the purpose for using a decorator is to override properties like
#getPrincipal()
, consider using
ServerWebExchange#mutate()
instead.
A FactoryBean implementation that takes an interface which must have one or more methods with the signatures
MyType xxx()
or
MyType xxx(MyIdType id)
(typically,
MyService getService()
or
MyService getService(String id)
) and creates a dynamic proxy which implements that interface, delegating to an underlying org.springframework.beans.factory.BeanFactory.
Such service locators permit the decoupling of calling code from the org.springframework.beans.factory.BeanFactory API, by using an appropriate custom locator interface. They will typically be used for prototype beans , i.e. for factory methods that are supposed to return a new instance for each call. The client receives a reference to the service locator via setter or constructor injection, to be able to invoke the locator's factory methods on demand. For singleton beans, direct setter or constructor injection of the target bean is preferable.
On invocation of the no-arg factory method, or the single-arg factory method with a String id of
null
or empty String, if exactly
one
bean in the factory matches the return type of the factory method, that bean is returned, otherwise a org.springframework.beans.factory.NoSuchBeanDefinitionException is thrown.
On invocation of the single-arg factory method with a non-null (and non-empty) argument, the proxy returns the result of a
org.springframework.beans.factory.BeanFactory#getBean(String)
call, using a stringified version of the passed-in id as bean name.
A factory method argument will usually be a String, but can also be an int or a custom enumeration type, for example, stringified via
toString
. The resulting String can be used as bean name as-is, provided that corresponding beans are defined in the bean factory. Alternatively,
a custom
between service IDs and bean names can be defined.
By way of an example, consider the following service locator interface. Note that this interface is not dependent on any Spring APIs.
package a.b.c; public interface ServiceFactory { public MyService getService(); }
A sample config in an XML-based org.springframework.beans.factory.BeanFactory might look as follows:
<beans> <!-- Prototype bean since we have state --> <bean id="myService" class="a.b.c.MyService" singleton="false"/> <!-- will lookup the above 'myService' bean by *TYPE* --> <bean id="myServiceFactory" class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean"> <property name="serviceLocatorInterface" value="a.b.c.ServiceFactory"/> </bean> <bean id="clientBean" class="a.b.c.MyClientBean"> <property name="myServiceFactory" ref="myServiceFactory"/> </bean> </beans>
The attendant
MyClientBean
class implementation might then look something like this:
package a.b.c; public class MyClientBean { private ServiceFactory myServiceFactory; // actual implementation provided by the Spring container public void setServiceFactory(ServiceFactory myServiceFactory) { this.myServiceFactory = myServiceFactory; } public void someBusinessMethod() { // get a 'fresh', brand new MyService instance MyService service = this.myServiceFactory.getService(); // use the service object to effect the business logic... } }
By way of an example that looks up a bean by name , consider the following service locator interface. Again, note that this interface is not dependent on any Spring APIs.
package a.b.c; public interface ServiceFactory { public MyService getService (String serviceName); }
A sample config in an XML-based org.springframework.beans.factory.BeanFactory might look as follows:
<beans> <!-- Prototype beans since we have state (both extend MyService) --> <bean id="specialService" class="a.b.c.SpecialService" singleton="false"/> <bean id="anotherService" class="a.b.c.AnotherService" singleton="false"/> <bean id="myServiceFactory" class="org.springframework.beans.factory.config.ServiceLocatorFactoryBean"> <property name="serviceLocatorInterface" value="a.b.c.ServiceFactory"/> </bean> <bean id="clientBean" class="a.b.c.MyClientBean"> <property name="myServiceFactory" ref="myServiceFactory"/> </bean> </beans>
The attendant
MyClientBean
class implementation might then look something like this:
package a.b.c; public class MyClientBean { private ServiceFactory myServiceFactory; // actual implementation provided by the Spring container public void setServiceFactory(ServiceFactory myServiceFactory) { this.myServiceFactory = myServiceFactory; } public void someBusinessMethod() { // get a 'fresh', brand new MyService instance MyService service = this.myServiceFactory.getService("specialService"); // use the service object to effect the business logic... } public void anotherBusinessMethod() { // get a 'fresh', brand new MyService instance MyService service = this.myServiceFactory.getService("anotherService"); // use the service object to effect the business logic... } }
See ObjectFactoryCreatingFactoryBean for an alternate approach.
org.springframework.web.context.ServletConfigAwareInterface to be implemented by any object that wishes to be notified of the ServletConfig (typically determined by the WebApplicationContext) that it runs in.
Note: Only satisfied if actually running within a Servlet-specific WebApplicationContext. Otherwise, no ServletConfig will be set.
org.springframework.web.context.support.ServletContextAttributeExporterExporter that takes Spring-defined objects and exposes them as ServletContext attributes. Usually, bean references will be used to export Spring-defined beans as ServletContext attributes.
Useful to make Spring-defined beans available to code that is not aware of Spring at all, but rather just of the Servlet API. Client code can then use plain ServletContext attribute lookups to access those objects, despite them being defined in a Spring application context.
Alternatively, consider using the WebApplicationContextUtils class to access Spring-defined beans via the WebApplicationContext interface. This makes client code aware of Spring API, of course.
org.springframework.web.context.support.ServletContextAttributeFactoryBeanFactoryBean that fetches a specific, existing ServletContext attribute. Exposes that ServletContext attribute when used as bean reference, effectively making it available as named Spring bean instance.
Intended to link in ServletContext attributes that exist before the startup of the Spring application context. Typically, such attributes will have been put there by third-party web frameworks. In a purely Spring-based web application, no such linking in of ServletContext attributes will be necessary.
NOTE: As of Spring 3.0, you may also use the "contextAttributes" default bean which is of type Map, and dereference it using an "#{contextAttributes.myKey}" expression to access a specific attribute by name.
org.springframework.web.context.support.ServletContextAwareProcessororg.springframework.beans.factory.config.BeanPostProcessor implementation that passes the ServletContext to beans that implement the ServletContextAware interface.
Web application contexts will automatically register this with their underlying bean factory. Applications do not use this directly.
org.springframework.web.context.support.ServletContextParameterFactoryBean
FactoryBean that retrieves a specific ServletContext init parameter (that is, a "context-param" defined in
web.xml
). Exposes that ServletContext init parameter when used as bean reference, effectively making it available as named Spring bean instance.
NOTE: As of Spring 3.0, you may also use the "contextParameters" default bean which is of type Map, and dereference it using an "#{contextParameters.myKey}" expression to access a specific parameter by name.
org.springframework.web.util.ServletContextPropertyUtilsHelper class for resolving placeholders in texts. Usually applied to file paths.
A text may contain
${...}
placeholders, to be resolved as servlet context init parameters or system properties: e.g.
${user.dir}
. Default values can be supplied using the ":" separator between key and value.
org.springframework.core.io.Resource implementation for javax.servlet.ServletContext resources, interpreting relative paths within the web application root directory.
Always supports stream access and URL access, but only allows
java.io.File
access when the web application archive is expanded.
ResourceLoader implementation that resolves paths as ServletContext resources, for use outside a WebApplicationContext (for example, in an HttpServletBean or GenericFilterBean subclass).
Within a WebApplicationContext, resource paths are automatically resolved as ServletContext resources by the context implementation.
org.springframework.web.context.support.ServletContextScopeScope wrapper for a ServletContext, i.e. for global web application attributes.
This differs from traditional Spring singletons in that it exposes attributes in the ServletContext. Those attributes will get destroyed whenever the entire application shuts down, which might be earlier or later than the shutdown of the containing Spring ApplicationContext.
The associated destruction mechanism relies on a org.springframework.web.context.ContextCleanupListener being registered in
web.xml
. Note that org.springframework.web.context.ContextLoaderListener includes ContextCleanupListener's functionality.
This scope is registered as default scope with key
"application"
.
An org.springframework.web.method.annotation.AbstractCookieValueMethodArgumentResolver that resolves cookie values from an HttpServletRequest.
org.springframework.web.servlet.mvc.ServletForwardingControllerSpring Controller implementation that forwards to a named servlet, i.e. the "servlet-name" in web.xml rather than a URL path mapping. A target servlet doesn't even need a "servlet-mapping" in web.xml in the first place: A "servlet" declaration is sufficient.
Useful to invoke an existing servlet via Spring's dispatching infrastructure, for example to apply Spring HandlerInterceptors to its requests. This will work even in a minimal Servlet container that does not support Servlet filters.
Example: web.xml, mapping all "/myservlet" requests to a Spring dispatcher. Also defines a custom "myServlet", but without servlet mapping.
<servlet> <servlet-name>myServlet</servlet-name> <servlet-class>mypackage.TestServlet</servlet-class> </servlet> <servlet> <servlet-name>myDispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>myDispatcher</servlet-name> <url-pattern>/myservlet</url-pattern> </servlet-mapping>
Example:
myDispatcher-servlet.xml, in turn forwarding "/myservlet" to your servlet (identified by servlet name). All such requests will go through the configured HandlerInterceptor chain (e.g. an OpenSessionInViewInterceptor). From the servlet point of view, everything will work as usual.
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="openSessionInViewInterceptor"/> </list> </property> <property name="mappings"> <props> <prop key="/myservlet">myServletForwardingController</prop> </props> </property> </bean> <bean id="myServletForwardingController" class="org.springframework.web.servlet.mvc.ServletForwardingController"> <property name="servletName"><value>myServlet</value></property> </bean>
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod
Extends InvocableHandlerMethod with the ability to handle return values through a registered HandlerMethodReturnValueHandler and also supports setting the response status based on a method-level
@ResponseStatus
annotation.
A
null
return value (including void) may be interpreted as the end of request processing in combination with a
@ResponseStatus
annotation, a not-modified check condition (see
ServletWebRequest#checkNotModified(long)
), or a method argument that provides access to the response stream.
A Servlet-specific ModelAttributeMethodProcessor that applies data binding through a WebDataBinder of type ServletRequestDataBinder.
Also adds a fall-back strategy to instantiate the model attribute from a URI template variable or from a request parameter if the name matches the model attribute name and there is an appropriate type conversion strategy.
org.springframework.web.bind.ServletRequestDataBinderSpecial org.springframework.validation.DataBinder to perform data binding from servlet request parameters to JavaBeans, including support for multipart files.
See the DataBinder/WebDataBinder superclasses for customization options, which include specifying allowed/required fields, and registering custom property editors.
Can also be used for manual data binding in custom web controllers: for example, in a plain Controller implementation or in a MultiActionController handler method. Simply instantiate a ServletRequestDataBinder for each binding process, and invoke
bind
with the current ServletRequest as argument:
MyBean myBean = new MyBean(); // apply binder to custom target object ServletRequestDataBinder binder = new ServletRequestDataBinder(myBean); // register custom editors, if desired binder.registerCustomEditor(...); // trigger actual binding of request parameters binder.bind(request); // optionally evaluate binding errors Errors errors = binder.getErrors(); ...
org.springframework.web.servlet.mvc.method.annotation.ServletRequestMethodArgumentResolver
Resolves request-related method argument values of the following types:
PropertyValues implementation created from parameters in a ServletRequest. Can look for all property values beginning with a certain prefix and prefix separator (default is "_").
For example, with a prefix of "spring", "spring_param1" and "spring_param2" result in a Map with "param1" and "param2" as keys.
This class is not immutable to be able to efficiently remove property values that should be ignored for binding.
org.springframework.web.bind.ServletRequestUtilsParameter extraction methods, for an approach distinct from data binding, in which parameters of specific types are required.
This approach is very useful for simple submissions, where binding request parameters to a command object would be overkill.
org.springframework.web.servlet.mvc.method.annotation.ServletResponseMethodArgumentResolverResolves response-related method argument values of types:
A FactoryBean for configuring javax.websocket.server.ServerContainer. Since there is usually only one
ServerContainer
instance accessible under a well-known
javax.servlet.ServletContext
attribute, simply declaring this FactoryBean and using its setters allows for configuring the
ServerContainer
through Spring configuration.
This is useful even if the
ServerContainer
is not injected into any other bean within the Spring application context. For example, an application can configure a org.springframework.web.socket.server.support.DefaultHandshakeHandler, a org.springframework.web.socket.sockjs.SockJsService, or ServerEndpointExporter, and separately declare this FactoryBean in order to customize the properties of the (one and only)
ServerContainer
instance.
UriComponentsBuilder with additional static factory methods to create links based on the current HttpServletRequest.
Note: This class extracts and uses values from the headers "Forwarded" ( RFC 7239 ), or "X-Forwarded-Host", "X-Forwarded-Port", and "X-Forwarded-Proto" if "Forwarded" is not found, in order to reflect the client-originated protocol and address. As an alternative consider using the org.springframework.web.filter.ForwardedHeaderFilter to have such headers extracted once and removed, or removed only (without being used). See the reference for further information including security considerations.
org.springframework.web.servlet.mvc.method.annotation.ServletWebArgumentResolverAdapterA Servlet-specific org.springframework.web.method.annotation.AbstractWebArgumentResolverAdapter that creates a NativeWebRequest from ServletRequestAttributes.
Note:
This class is provided for backwards compatibility. However it is recommended to re-write a
WebArgumentResolver
as
HandlerMethodArgumentResolver
. For more details see javadoc of org.springframework.web.method.annotation.AbstractWebArgumentResolverAdapter.
Spring Controller implementation that wraps a servlet instance which it manages internally. Such a wrapped servlet is not known outside of this controller; its entire lifecycle is covered here (in contrast to ServletForwardingController).
Useful to invoke an existing servlet via Spring's dispatching infrastructure, for example to apply Spring HandlerInterceptors to its requests.
Note that Struts has a special requirement in that it parses
web.xml
to find its servlet mapping. Therefore, you need to specify the DispatcherServlet's servlet name as "servletName" on this controller, so that Struts finds the DispatcherServlet's mapping (thinking that it refers to the ActionServlet).
Example: a DispatcherServlet XML context, forwarding "*.do" to the Struts ActionServlet wrapped by a ServletWrappingController. All such requests will go through the configured HandlerInterceptor chain (e.g. an OpenSessionInViewInterceptor). From the Struts point of view, everything will work as usual.
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="interceptors"> <list> <ref bean="openSessionInViewInterceptor"/> </list> </property> <property name="mappings"> <props> <prop key="*.do">strutsWrappingController</prop> </props> </property> </bean> <bean id="strutsWrappingController" class="org.springframework.web.servlet.mvc.ServletWrappingController"> <property name="servletClass"> <value>org.apache.struts.action.ActionServlet</value> </property> <property name="servletName"> <value>action</value> </property> <property name="initParameters"> <props> <prop key="config">/WEB-INF/struts-config.xml</prop> </props> </property> </bean>
org.springframework.web.bind.annotation.SessionAttribute
Annotation to bind a method parameter to a session attribute.
The main motivation is to provide convenient access to existing, permanent session attributes (e.g. user authentication object) with an optional/required check and a cast to the target method parameter type.
For use cases that require adding or removing session attributes consider injecting
org.springframework.web.context.request.WebRequest
or
javax.servlet.http.HttpSession
into the controller method.
For temporary storage of model attributes in the session as part of the workflow for a controller, consider using SessionAttributes instead.
org.springframework.web.reactive.result.method.annotation.SessionAttributeMethodArgumentResolverResolves method arguments annotated with an @SessionAttribute.
org.springframework.web.servlet.mvc.method.annotation.SessionAttributeMethodArgumentResolverResolves method arguments annotated with an @SessionAttribute.
org.springframework.web.bind.annotation.SessionAttributesAnnotation that indicates the session attributes that a specific handler uses.
This will typically list the names of model attributes which should be transparently stored in the session or some conversational storage, serving as form-backing beans. Declared at the type level , applying to the model attributes that the annotated handler class operates on.
NOTE: Session attributes as indicated using this annotation correspond to a specific handler's model attributes, getting transparently stored in a conversational session. Those attributes will be removed once the handler indicates completion of its conversational session. Therefore, use this facility for such conversational attributes which are supposed to be stored in the session temporarily during the course of a specific handler's conversation.
For permanent session attributes, e.g. a user authentication object, use the traditional
session.setAttribute
method instead. Alternatively, consider using the attribute management capabilities of the generic org.springframework.web.context.request.WebRequest interface.
NOTE:
When using controller interfaces (e.g. for AOP proxying), make sure to consistently put
all
your mapping annotations — such as
@RequestMapping
and
@SessionAttributes
— on the controller
interface
rather than on the implementation class.
Manages controller-specific session attributes declared via SessionAttributes. Actual storage is delegated to a SessionAttributeStore instance.
When a controller annotated with
@SessionAttributes
adds attributes to its model, those attributes are checked against names and types specified via
@SessionAttributes
. Matching model attributes are saved in the HTTP session and remain there until the controller calls
SessionStatus#setComplete()
.
Callback for executing any number of operations on a provided Session.
To be used with the
JmsTemplate#execute(SessionCallback)
method, often implemented as an anonymous inner class or as a lambda expression.
Event raised when a new WebSocket client using a Simple Messaging Protocol (e.g. STOMP) as the WebSocket sub-protocol issues a connect request.
Note that this is not the same as the WebSocket session getting established but rather the client's first attempt to connect within the sub-protocol, for example sending the STOMP CONNECT frame.
org.springframework.web.socket.messaging.SessionDisconnectEventEvent raised when the session of a WebSocket client using a Simple Messaging Protocol (e.g. STOMP) as the WebSocket sub-protocol is closed.
Note that this event may be raised more than once for a single session and therefore event consumers should be idempotent and ignore a duplicate event.
org.springframework.orm.hibernate5.SessionHolderSession holder, wrapping a Hibernate Session and a Hibernate Transaction. HibernateTransactionManager binds instances of this class to the thread, for a given SessionFactory.
Note: This is an SPI class, not intended to be used by applications.
org.springframework.web.servlet.i18n.SessionLocaleResolverorg.springframework.web.servlet.LocaleResolver implementation that uses a locale attribute in the user's session in case of a custom setting, with a fallback to the specified default locale or the request's accept-header locale.
This is most appropriate if the application needs user sessions anyway, i.e. when the
HttpSession
does not have to be created just for storing the user's locale. The session may optionally contain an associated time zone attribute as well; alternatively, you may specify a default time zone.
Custom controllers can override the user's locale and time zone by calling
#setLocale(Context)
on the resolver, e.g. responding to a locale change request. As a more convenient alternative, consider using
org.springframework.web.servlet.support.RequestContext#changeLocale
.
In contrast to CookieLocaleResolver, this strategy stores locally chosen locale settings in the Servlet container's
HttpSession
. As a consequence, those settings are just temporary for each session and therefore lost when each session terminates.
Note that there is no direct relationship with external session management mechanisms such as the "Spring Session" project. This
LocaleResolver
will simply evaluate and modify corresponding
HttpSession
attributes against the current
HttpServletRequest
.
Session-backed org.springframework.beans.factory.config.Scope implementation.
Relies on a thread-bound RequestAttributes instance, which can be exported through RequestContextListener, org.springframework.web.filter.RequestContextFilter or org.springframework.web.servlet.DispatcherServlet.
org.springframework.web.context.annotation.SessionScope
@SessionScope
is a specialization of Scope for a component whose lifecycle is bound to the current web session.
Specifically,
@SessionScope
is a
composed annotation
that acts as a shortcut for
@Scope("session")
with the default
#proxyMode
set to
TARGET_CLASS
.
@SessionScope
may be used as a meta-annotation to create custom composed annotations.
Resolver for a SessionStatus argument obtaining it from the BindingContext.
org.springframework.web.servlet.theme.SessionThemeResolverorg.springframework.web.servlet.ThemeResolver implementation that uses a theme attribute in the user's session in case of a custom setting, with a fallback to the default theme. This is most appropriate if the application needs user sessions anyway.
Custom controllers can override the user's theme by calling
setThemeName
, e.g. responding to a theme change request.
A ListenableFuture whose value can be set via
#set(Object)
or
#setException(Throwable)
. It may also get cancelled.
Inspired by
com.google.common.util.concurrent.SettableFuture
.
javax.servlet.Filter that generates an
ETag
value based on the content on the response. This ETag is compared to the
If-None-Match
header of the request. If these headers are equal, the response content is not sent, but rather a
304 "Not Modified"
status instead.
Since the ETag is based on the response content, the response (e.g. a org.springframework.web.servlet.View) is still rendered. As such, this filter only saves bandwidth, not server performance.
NOTE: As of Spring Framework 5.0, this filter uses request/response decorators built on the Servlet 3.1 API.
org.springframework.orm.jpa.support.SharedEntityManagerBeanFactoryBean that exposes a shared JPA javax.persistence.EntityManager reference for a given EntityManagerFactory. Typically used for an EntityManagerFactory created by org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean, as direct alternative to a JNDI lookup for a Java EE server's EntityManager reference.
The shared EntityManager will behave just like an EntityManager fetched from an application server's JNDI environment, as defined by the JPA specification. It will delegate all calls to the current transactional EntityManager, if any; otherwise, it will fall back to a newly created EntityManager per operation.
Can be passed to DAOs that expect a shared EntityManager reference rather than an EntityManagerFactory. Note that Spring's org.springframework.orm.jpa.JpaTransactionManager always needs an EntityManagerFactory in order to create new transactional EntityManager instances.
org.springframework.orm.jpa.SharedEntityManagerCreatorDelegate for creating a shareable JPA javax.persistence.EntityManager reference for a given javax.persistence.EntityManagerFactory.
A shared EntityManager will behave just like an EntityManager fetched from an application server's JNDI environment, as defined by the JPA specification. It will delegate all calls to the current transactional EntityManager, if any; otherwise it will fall back to a newly created EntityManager per operation.
For a behavioral definition of such a shared transactional EntityManager, see
javax.persistence.PersistenceContextType#TRANSACTION
and its discussion in the JPA spec document. This is also the default being used for the annotation-based
javax.persistence.PersistenceContext#type()
.
MockMvcConfigurer that stores and re-uses the HTTP session across multiple requests performed through the same
MockMvc
instance.
Example use:
import static org.springframework.test.web.servlet.setup.SharedHttpSessionConfigurer.sharedHttpSession; // ... MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new TestController()) .apply(sharedHttpSession()) .build(); // Use mockMvc to perform requests ...
org.springframework.messaging.simp.SimpMessageMappingInfo
Encapsulates the following request mapping conditions:
A Scope implementation exposing the attributes of a SiMP session (e.g. WebSocket session).
Relies on a thread-bound SimpAttributes instance exported by org.springframework.messaging.simp.annotation.support.SimpAnnotationMethodMessageHandler.
org.springframework.context.event.SimpleApplicationEventMulticasterSimple implementation of the ApplicationEventMulticaster interface.
Multicasts all events to all registered listeners, leaving it up to the listeners to ignore events that they are not interested in. Listeners will usually perform corresponding
instanceof
checks on the passed-in event object.
By default, all listeners are invoked in the calling thread. This allows the danger of a rogue listener blocking the entire application, but adds minimal overhead. Specify an alternative task executor to have listeners executed in different threads, for example from a thread pool.
org.springframework.jca.support.SimpleBootstrapContextSimple implementation of the JCA 1.7 javax.resource.spi.BootstrapContext interface, used for bootstrapping a JCA ResourceAdapter in a local environment.
Delegates to the given WorkManager and XATerminator, if any. Creates simple local instances of
java.util.Timer
.
CommandLinePropertySource implementation backed by a simple String array. Purpose This
CommandLinePropertySource
implementation aims to provide the simplest possible approach to parsing command line arguments. As with all
CommandLinePropertySource
implementations, command line arguments are broken into two distinct groups:
option arguments
and
non-option arguments
, as described below
(some sections copied from Javadoc for SimpleCommandLineArgsParser)
: Working with option arguments Option arguments must adhere to the exact syntax:
--optName[=optValue]
That is, options must be prefixed with "
--
", and may or may not specify a value. If a value is specified, the name and value must be separated
without spaces
by an equals sign ("="). Valid examples of option arguments
--foo --foo=bar --foo="bar then baz" --foo=bar,baz,biz
Invalid examples of option arguments
-foo --foo bar --foo = bar --foo=bar --foo=baz --foo=biz
Working with non-option arguments Any and all arguments specified at the command line without the "
--
" option prefix will be considered as "non-option arguments" and made available through the
#getNonOptionArgs()
method. Typical usage
public static void main(String[] args) { PropertySource ps = new SimpleCommandLinePropertySource(args); // ... }
See CommandLinePropertySource for complete general usage examples. Beyond the basics
When more fully-featured command line parsing is necessary, consider using the provided JOptCommandLinePropertySource, or implement your own
CommandLinePropertySource
against the command line parsing library of your choice!
Simple
NamespaceHandler
implementation that maps custom attributes directly through to bean properties. An important point to note is that this
NamespaceHandler
does not have a corresponding schema since there is no way to know in advance all possible attribute names.
An example of the usage of this
NamespaceHandler
is shown below:
<bean id="author" class="..TestBean" c:name="Enescu" c:work-ref="compositions"/>
Here the '
c:name
' corresponds directly to the '
name
' argument declared on the constructor of class '
TestBean
'. The '
c:work-ref
' attributes corresponds to the '
work
' argument and, rather than being the concrete value, it contains the name of the bean that will be considered as a parameter.
Note
: This implementation supports only named parameters - there is no support for indexes or types. Further more, the names are used as hints by the container which, by default, does type introspection.
org.springframework.jdbc.datasource.SimpleDriverDataSource
Simple implementation of the standard JDBC javax.sql.DataSource interface, configuring a plain old JDBC java.sql.Driver via bean properties, and returning a new java.sql.Connection from every
getConnection
call.
NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call.
In a Java EE container, it is recommended to use a JNDI DataSource provided by the container. Such a DataSource can be exposed as a DataSource bean in a Spring ApplicationContext via org.springframework.jndi.JndiObjectFactoryBean, for seamless switching to and from a local DataSource bean like this class.
If you need a "real" connection pool outside of a Java EE container, consider Apache Commons DBCP or C3P0 . Commons DBCP's BasicDataSource and C3P0's ComboPooledDataSource are full connection pool beans, supporting the same basic properties as this class plus specific settings (such as minimal/maximal pool size etc).
org.springframework.remoting.caucho.SimpleHessianServiceExporterHTTP request handler that exports the specified service bean as Hessian service endpoint, accessible via a Hessian proxy. Designed for Sun's JRE 1.6 HTTP server, implementing the com.sun.net.httpserver.HttpHandler interface.
Hessian is a slim, binary RPC protocol. For information on Hessian, see the Hessian website . Note: As of Spring 4.0, this exporter requires Hessian 4.0 or above.
Hessian services exported with this class can be accessed by any Hessian client, as there isn't any special handling involved.
org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutorHttpInvokerRequestExecutor implementation that uses standard J2SE facilities to execute POST requests, without support for HTTP authentication or advanced configuration options.
Designed for easy subclassing, customizing specific template methods. However, consider
HttpComponentsHttpInvokerRequestExecutor
for more sophisticated needs: The J2SE HttpURLConnection is rather limited in its capabilities.
HTTP request handler that exports the specified service bean as HTTP invoker service endpoint, accessible via an HTTP invoker proxy. Designed for Sun's JRE 1.6 HTTP server, implementing the com.sun.net.httpserver.HttpHandler interface.
Deserializes remote invocation objects and serializes remote invocation result objects. Uses Java serialization just like RMI, but provides the same ease of setup as Caucho's HTTP-based Hessian protocol.
HTTP invoker is the recommended protocol for Java-to-Java remoting. It is more powerful and more extensible than Hessian, at the expense of being tied to Java. Nevertheless, it is as easy to set up as Hessian, which is its main advantage compared to RMI.
WARNING: Be aware of vulnerabilities due to unsafe Java deserialization: Manipulated input streams could lead to unwanted code execution on the server during the deserialization step. As a consequence, do not expose HTTP invoker endpoints to untrusted clients but rather just between your own services. In general, we strongly recommend any other message format (e.g. JSON) instead.
org.springframework.remoting.support.SimpleHttpServerFactoryBeanorg.springframework.beans.factory.FactoryBean that creates a simple HTTP server, based on the HTTP server that is included in Sun's JRE 1.6. Starts the HTTP server on initialization and stops it on destruction. Exposes the resulting com.sun.net.httpserver.HttpServer object.
Allows for registering com.sun.net.httpserver.HttpHandler for specific
context paths
. Alternatively, register such context-specific handlers programmatically on the com.sun.net.httpserver.HttpServer itself.
Simple exporter for JAX-WS services, autodetecting annotated service beans (through the JAX-WS javax.jws.WebService annotation) and exporting them through the HTTP server included in Sun's JDK 1.6. The full address for each service will consist of the server's base address with the service name appended (e.g. "http://localhost:8080/OrderService").
Note that this exporter will only work on Sun's JDK 1.6 or higher, as well as on JDKs that ship Sun's entire class library as included in the Sun JDK. For a portable JAX-WS exporter, have a look at SimpleJaxWsServiceExporter.
org.springframework.beans.factory.support.SimpleInstantiationStrategySimple object instantiation strategy for use in a BeanFactory.
Does not support Method Injection, although it provides hooks for subclasses to override to add Method Injection support, for example by overriding methods.
org.springframework.remoting.jaxws.SimpleJaxWsServiceExporterSimple exporter for JAX-WS services, autodetecting annotated service beans (through the JAX-WS javax.jws.WebService annotation) and exporting them with a configured base address (by default "http://localhost:8080/") using the JAX-WS provider's built-in publication support. The full address for each service will consist of the base address with the service name appended (e.g. "http://localhost:8080/OrderService").
Note that this exporter will only work if the JAX-WS runtime actually supports publishing with an address argument, i.e. if the JAX-WS runtime ships an internal HTTP server. This is the case with the JAX-WS runtime that's included in Sun's JDK 6 but not with the standalone JAX-WS 2.1 RI.
For explicit configuration of JAX-WS endpoints with Sun's JDK 6 HTTP server, consider using SimpleHttpServerJaxWsServiceExporter!
org.springframework.jdbc.core.simple.SimpleJdbcInsertA SimpleJdbcInsert is a multi-threaded, reusable object providing easy insert capabilities for a table. It provides meta data processing to simplify the code needed to construct a basic insert statement. All you need to provide is the name of the table and a Map containing the column names and the column values.
The meta data processing is based on the DatabaseMetaData provided by the JDBC driver. As long as the JDBC driver can provide the names of the columns for a specified table than we can rely on this auto-detection feature. If that is not the case, then the column names must be specified explicitly.
The actual insert is being handled using Spring's org.springframework.jdbc.core.JdbcTemplate.
Many of the configuration methods return the current instance of the SimpleJdbcInsert to provide the ability to chain multiple ones together in a "fluent" interface style.
org.springframework.cache.interceptor.SimpleKeyGeneratorSimple key generator. Returns the parameter itself if a single non-null value is given, otherwise returns a SimpleKey of the parameters.
No collisions will occur with the keys generated by this class. The returned SimpleKey object can be safely used with a org.springframework.cache.concurrent.ConcurrentMapCache, however, might not be suitable for all org.springframework.cache.Cache implementations.
org.springframework.instrument.classloading.SimpleLoadTimeWeaver
LoadTimeWeaver
that builds and exposes a SimpleInstrumentableClassLoader.
Mainly intended for testing environments, where it is sufficient to perform all class transformation on a newly created
ClassLoader
instance.
Originally a simple Commons Logging provider configured by system properties. Deprecated in
spring-jcl
, effectively equivalent to NoOpLog now.
Instead of instantiating this directly, call
LogFactory#getLog(Class/String)
which will fall back to
java.util.logging
if neither Log4j nor SLF4J are present.
org.springframework.web.servlet.HandlerExceptionResolver implementation that allows for mapping exception class names to view names, either for a set of given handlers or for all handlers in the DispatcherServlet.
Error views are analogous to error page JSPs, but can be used with any kind of exception including any checked one, with fine-granular mappings for specific handlers.
org.springframework.mock.jndi.SimpleNamingContextSimple implementation of a JNDI naming context. Only supports binding plain Objects to String names. Mainly for test environments, but also usable for standalone applications.
This class is not intended for direct usage by applications, although it can be used for example to override JndiTemplate's
createInitialContext
method in unit tests. Typically, SimpleNamingContextBuilder will be used to set up a JVM-level JNDI environment.
Simple
NamespaceHandler
implementation that maps custom attributes directly through to bean properties. An important point to note is that this
NamespaceHandler
does not have a corresponding schema since there is no way to know in advance all possible attribute names.
An example of the usage of this
NamespaceHandler
is shown below:
<bean id="rob" class="..TestBean" p:name="Rob Harrop" p:spouse-ref="sally"/>
Here the '
p:name
' corresponds directly to the '
name
' property on class '
TestBean
'. The '
p:spouse-ref
' attributes corresponds to the '
spouse
' property and, rather than being the concrete value, it contains the name of the bean that will be injected into that property.
org.springframework.ejb.access.SimpleRemoteSlsbInvokerInterceptor
Basic invoker for a remote Stateless Session Bean. Designed for EJB 2.x, but works for EJB 3 Session Beans as well.
"Creates" a new EJB instance for each invocation, or caches the session bean instance for all invocations (see
#setCacheSessionBean
). See org.springframework.jndi.JndiObjectLocator for info on how to specify the JNDI location of the target EJB.
In a bean container, this class is normally best used as a singleton. However, if that bean container pre-instantiates singletons (as do the XML ApplicationContext variants) you may have a problem if the bean container is loaded before the EJB container loads the target EJB. That is because by default the JNDI lookup will be performed in the init method of this class and cached, but the EJB will not have been bound at the target location yet. The best solution is to set the "lookupHomeOnStartup" property to "false", in which case the home will be fetched on first access to the EJB. (This flag is only true by default for backwards compatibility reasons).
This invoker is typically used with an RMI business interface, which serves as super-interface of the EJB component interface. Alternatively, this invoker can also proxy a remote SLSB with a matching non-RMI business interface, i.e. an interface that mirrors the EJB business methods but does not declare RemoteExceptions. In the latter case, RemoteExceptions thrown by the EJB stub will automatically get converted to Spring's unchecked RemoteAccessException.
org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBeanConvenient FactoryBean for remote SLSB proxies. Designed for EJB 2.x, but works for EJB 3 Session Beans as well.
See org.springframework.jndi.JndiObjectLocator for info on how to specify the JNDI location of the target EJB.
If you want control over interceptor chaining, use an AOP ProxyFactoryBean with SimpleRemoteSlsbInvokerInterceptor rather than rely on this class.
In a bean container, this class is normally best used as a singleton. However, if that bean container pre-instantiates singletons (as do the XML ApplicationContext variants) you may have a problem if the bean container is loaded before the EJB container loads the target EJB. That is because by default the JNDI lookup will be performed in the init method of this class and cached, but the EJB will not have been bound at the target location yet. The best solution is to set the lookupHomeOnStartup property to false, in which case the home will be fetched on first access to the EJB. (This flag is only true by default for backwards compatibility reasons).
This proxy factory is typically used with an RMI business interface, which serves as super-interface of the EJB component interface. Alternatively, this factory can also proxy a remote SLSB with a matching non-RMI business interface, i.e. an interface that mirrors the EJB business methods but does not declare RemoteExceptions. In the latter case, RemoteExceptions thrown by the EJB stub will automatically get converted to Spring's unchecked RemoteAccessException.
org.springframework.test.web.client.SimpleRequestExpectationManager
Simple
RequestExpectationManager
that matches requests to expectations sequentially, i.e. in the order of declaration of expectations.
When request expectations have an expected count greater than one, only the first execution is expected to match the order of declaration. Subsequent request executions may be inserted anywhere thereafter.
org.springframework.web.servlet.handler.SimpleServletHandlerAdapter
Adapter to use the Servlet interface with the generic DispatcherServlet. Calls the Servlet's
service
method to handle a request.
Last-modified checking is not explicitly supported: This is typically handled by the Servlet implementation itself (usually deriving from the HttpServlet base class).
This adapter is not activated by default; it needs to be defined as a bean in the DispatcherServlet context. It will automatically apply to mapped handler beans that implement the Servlet interface then.
Note that Servlet instances defined as bean will not receive initialization and destruction callbacks, unless a special post-processor such as SimpleServletPostProcessor is defined in the DispatcherServlet context.
Alternatively, consider wrapping a Servlet with Spring's ServletWrappingController. This is particularly appropriate for existing Servlet classes, allowing to specify Servlet initialization parameters etc.
org.springframework.web.servlet.handler.SimpleServletPostProcessororg.springframework.beans.factory.config.BeanPostProcessor that applies initialization and destruction callbacks to beans that implement the javax.servlet.Servlet interface.
After initialization of the bean instance, the Servlet
init
method will be called with a ServletConfig that contains the bean name of the Servlet and the ServletContext that it is running in.
Before destruction of the bean instance, the Servlet
destroy
will be called.
Note that this post-processor does not support Servlet initialization parameters. Bean instances that implement the Servlet interface are supposed to be configured like any other Spring bean, that is, through constructor arguments or bean properties.
For reuse of a Servlet implementation in a plain Servlet container and as a bean in a Spring context, consider deriving from Spring's org.springframework.web.servlet.HttpServletBean base class that applies Servlet initialization parameters as bean properties, supporting both the standard Servlet and the Spring bean initialization style.
Alternatively, consider wrapping a Servlet with Spring's org.springframework.web.servlet.mvc.ServletWrappingController. This is particularly appropriate for existing Servlet classes, allowing to specify Servlet initialization parameters etc.
org.springframework.jca.work.SimpleTaskWorkManagerSimple JCA 1.7 javax.resource.spi.work.WorkManager implementation that delegates to a Spring org.springframework.core.task.TaskExecutor. Provides simple task execution including start timeouts, but without support for a JCA ExecutionContext (i.e. without support for imported transactions).
Uses a org.springframework.core.task.SyncTaskExecutor for
#doWork
calls and a org.springframework.core.task.SimpleAsyncTaskExecutor for
#startWork
and
#scheduleWork
calls, by default. These default task executors can be overridden through configuration.
NOTE: This WorkManager does not provide thread pooling by default! Specify a org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor (or any other thread-pooling TaskExecutor) as "asyncTaskExecutor" in order to achieve actual thread pooling.
This WorkManager automatically detects a specified org.springframework.core.task.AsyncTaskExecutor implementation and uses its extended timeout functionality where appropriate. JCA WorkListeners are fully supported in any case.
org.springframework.scheduling.quartz.SimpleThreadPoolTaskExecutorSubclass of Quartz's SimpleThreadPool that implements Spring's org.springframework.core.task.TaskExecutor interface and listens to Spring lifecycle callbacks.
Can be shared between a Quartz Scheduler (specified as "taskExecutor") and other TaskExecutor users, or even used completely independent of a Quartz Scheduler (as plain TaskExecutor backend).
org.springframework.context.support.SimpleThreadScopeA simple thread-backed Scope implementation.
NOTE:
This thread scope is not registered by default in common contexts. Instead, you need to explicitly assign it to a scope key in your setup, either through
org.springframework.beans.factory.config.ConfigurableBeanFactory#registerScope
or through a org.springframework.beans.factory.config.CustomScopeConfigurer bean.
SimpleThreadScope
does not clean up any objects
associated with it. As such, it is typically preferable to use org.springframework.web.context.request.RequestScope in web environments.
For an implementation of a thread-based
Scope
with support for destruction callbacks, refer to the
Spring by Example Custom Thread Scope Module
.
Thanks to Eugene Kuleshov for submitting the original prototype for a thread scope!
org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext
Simple implementation of the TimeZoneAwareLocaleContext interface, always returning a specified
Locale
and
TimeZone
.
Note: Prefer the use of SimpleLocaleContext when only setting a Locale but no TimeZone.
org.springframework.transaction.jta.SimpleTransactionFactoryDefault implementation of the TransactionFactory strategy interface, simply wrapping a standard JTA javax.transaction.TransactionManager.
Does not support transaction names; simply ignores any specified name.
org.springframework.transaction.support.SimpleTransactionScopeA simple transaction-backed Scope implementation, delegating to TransactionSynchronizationManager's resource binding mechanism.
NOTE:
Like org.springframework.context.support.SimpleThreadScope, this transaction scope is not registered by default in common contexts. Instead, you need to explicitly assign it to a scope key in your setup, either through
org.springframework.beans.factory.config.ConfigurableBeanFactory#registerScope
or through a org.springframework.beans.factory.config.CustomScopeConfigurer bean.
A simple org.springframework.transaction.TransactionStatus implementation.
Derives from AbstractTransactionStatus and adds an explicit
"newTransaction"
flag.
This class is not used by any of Spring's pre-built org.springframework.transaction.PlatformTransactionManager implementations. It is mainly provided as a start for custom transaction manager implementations and as a static mock for testing transactional code (either as part of a mock
PlatformTransactionManager
or as argument passed into a TransactionCallback to be tested).
A Spring FactoryBean for creating a Quartz org.quartz.SimpleTrigger instance, supporting bean-style usage for trigger configuration.
SimpleTrigger(Impl)
itself is already a JavaBean but lacks sensible defaults. This class uses the Spring bean name as job name, the Quartz default group ("DEFAULT") as job group, the current time as start time, and indefinite repetition, if not specified.
This class will also register the trigger with the job name and group of a given org.quartz.JobDetail. This allows SchedulerFactoryBean to automatically register a trigger for the corresponding JobDetail, instead of registering the JobDetail separately.
org.springframework.web.reactive.handler.SimpleUrlHandlerMappingImplementation of the org.springframework.web.reactive.HandlerMapping interface to map from URLs to request handler beans. Supports both mapping to bean instances and mapping to bean names; the latter is required for non-singleton handlers.
The "urlMap" property is suitable for populating the handler map with bean instances. Mappings to bean names can be set via the "mappings" property, in a form accepted by the
java.util.Properties
class, like as follows:
/welcome.html=ticketController /show.html=ticketController
The syntax is
PATH=HANDLER_BEAN_NAME
. If the path doesn't begin with a slash, one is prepended.
Supports direct matches, e.g. a registered "/test" matches "/test", and various Ant-style pattern matches, e.g. a registered "/t*" pattern matches both "/test" and "/team", "/test/*" matches all paths under "/test", "/test/**" matches all paths below "/test". For details, see the org.springframework.web.util.pattern.PathPattern javadoc.
org.springframework.web.servlet.handler.SimpleUrlHandlerMappingImplementation of the org.springframework.web.servlet.HandlerMapping interface to map from URLs to request handler beans. Supports both mapping to bean instances and mapping to bean names; the latter is required for non-singleton handlers.
The "urlMap" property is suitable for populating the handler map with bean references, e.g. via the map element in XML bean definitions.
Mappings to bean names can be set via the "mappings" property, in a form accepted by the
java.util.Properties
class, like as follows:
/welcome.html=ticketController /show.html=ticketController
The syntax is
PATH=HANDLER_BEAN_NAME
. If the path doesn't begin with a slash, one is prepended.
Supports direct matches (given "/test" -> registered "/test") and "*" pattern matches (given "/test" -> registered "/t*"). Note that the default is to map within the current servlet mapping if applicable; see the
"alwaysUseFullPath"
property. For details on the pattern options, see the org.springframework.util.AntPathMatcher javadoc.
RowMapper implementation that converts a single column into a single result value per row. Expects to operate on a
java.sql.ResultSet
that just contains a single column.
The type of the result value for each row can be specified. The value for the single column will be extracted from the
ResultSet
and converted into the specified target type.
Implementation of SmartDataSource that wraps a single JDBC Connection which is not closed after use. Obviously, this is not multi-threading capable.
Note that at shutdown, someone should close the underlying Connection via the
close()
method. Client code will never call close on the Connection handle if it is SmartDataSource-aware (e.g. uses
DataSourceUtils.releaseConnection
).
If client code will call
close()
in the assumption of a pooled Connection, like when using persistence tools, set "suppressClose" to "true". This will return a close-suppressing proxy instead of the physical Connection.
This is primarily intended for testing. For example, it enables easy testing outside an application server, for code that expects to work on a DataSource. In contrast to DriverManagerDataSource, it reuses the same Connection all the time, avoiding excessive creation of physical Connections.
org.springframework.jca.cci.connection.SingleConnectionFactory
A CCI ConnectionFactory adapter that returns the same Connection on all
getConnection
calls, and ignores calls to
Connection.close()
.
Useful for testing and standalone environments, to keep using the same Connection for multiple CciTemplate calls, without having a pooling ConnectionFactory, also spanning any number of transactions.
You can either pass in a CCI Connection directly, or let this factory lazily create a Connection via a given target ConnectionFactory.
org.springframework.context.event.SmartApplicationListenerExtended variant of the standard ApplicationListener interface, exposing further metadata such as the supported event type.
Users are strongly advised to use the GenericApplicationListener interface instead as it provides an improved detection of generics-based event types.
org.springframework.core.SmartClassLoaderInterface to be implemented by a reloading-aware ClassLoader (e.g. a Groovy-based ClassLoader). Detected for example by Spring's CGLIB proxy factory for making a caching decision.
If a ClassLoader does not implement this interface, then all of the classes obtained from it should be considered as not reloadable (i.e. cacheable).
org.springframework.beans.factory.SmartFactoryBean
Extension of the FactoryBean interface. Implementations may indicate whether they always return independent instances, for the case where their
#isSingleton()
implementation returning
false
does not clearly indicate independent instances.
Plain FactoryBean implementations which do not implement this extended interface are simply assumed to always return independent instances if their
#isSingleton()
implementation returns
false
; the exposed object is only accessed on demand.
NOTE: This interface is a special purpose interface, mainly for internal use within the framework and within collaborating frameworks. In general, application-provided FactoryBeans should simply implement the plain FactoryBean interface. New methods might be added to this extended interface even in point releases.
org.springframework.beans.factory.SmartInitializingSingleton
Callback interface triggered at the end of the singleton pre-instantiation phase during BeanFactory bootstrap. This interface can be implemented by singleton beans in order to perform some initialization after the regular singleton instantiation algorithm, avoiding side effects with accidental early initialization (e.g. from
ListableBeanFactory#getBeansOfType
calls). In that sense, it is an alternative to InitializingBean which gets triggered right at the end of a bean's local construction phase.
This callback variant is somewhat similar to org.springframework.context.event.ContextRefreshedEvent but doesn't require an implementation of org.springframework.context.ApplicationListener, with no need to filter context references across a context hierarchy etc. It also implies a more minimal dependency on just the
beans
package and is being honored by standalone ListableBeanFactory implementations, not just in an org.springframework.context.ApplicationContext environment.
NOTE: If you intend to start/manage asynchronous tasks, preferably implement org.springframework.context.Lifecycle instead which offers a richer model for runtime management and allows for phased startup/shutdown.
org.springframework.web.socket.sockjs.client.SockJsClientA SockJS implementation of org.springframework.web.socket.client.WebSocketClient with fallback alternatives that simulate a WebSocket interaction through plain HTTP streaming and long polling techniques..
Implements Lifecycle in order to propagate lifecycle events to the transports it is configured with.
org.springframework.web.socket.sockjs.SockJsMessageDeliveryExceptionAn exception thrown when a message frame was successfully received over an HTTP POST and parsed but one or more of the messages it contained could not be delivered to the WebSocketHandler either because the handler failed or because the connection got closed.
The SockJS session is not automatically closed after this exception.
org.springframework.web.socket.sockjs.transport.handler.SockJsWebSocketHandlerAn implementation of WebSocketHandler that adds SockJS messages frames, sends SockJS heartbeat messages, and delegates lifecycle events and messages to a target WebSocketHandler.
Methods in this class allow exceptions from the wrapped WebSocketHandler to propagate. However, any exceptions resulting from SockJS message handling (e.g. while sending SockJS frames or heartbeat messages) are caught and treated as transport errors, i.e. routed to the
handleTransportError
method of the wrapped handler and the session closed.
Simple utility methods for working with network sockets — for example, for finding available ports on
localhost
.
Within this class, a TCP port refers to a port for a ServerSocket; whereas, a UDP port refers to a port for a DatagramSocket.
org.springframework.context.event.SourceFilteringListenerorg.springframework.context.ApplicationListener decorator that filters events from a specified event source, invoking its delegate listener for matching org.springframework.context.ApplicationEvent objects only.
Can also be used as base class, overriding the
#onApplicationEventInternal
method instead of specifying a delegate listener.
A SpelCompiler will take a regular parsed expression and create (and load) a class containing byte code that does the same thing as that expression. The compiled form of an expression will evaluate far faster than the interpreted form.
The SpelCompiler is not currently handling all expression types but covers many of the common cases. The framework is extensible to cover more cases in the future. For absolute maximum speed there is *no checking* in the compiled code. The compiled version of the expression uses information learned during interpreted runs of the expression when it generates the byte code. For example if it knows that a particular property dereference always seems to return a Map then it will generate byte code that expects the result of the property dereference to be a Map. This ensures maximal performance but should the dereference result in something other than a map, the compiled expression will fail - like a ClassCastException would occur if passing data of an unexpected type in a regular Java program.
Due to the lack of checking there are likely some expressions that should never be compiled, for example if an expression is continuously dealing with different types of data. Due to these cases the compiler is something that must be selectively turned on for an associated SpelExpressionParser (through the SpelParserConfiguration object), it is not on by default.
Individual expressions can be compiled by calling
SpelCompiler.compile(expression)
.
Utility class exposing constants related to Spring's internal repackaging of the ASM bytecode manipulation library (currently based on version 6.0).
See
package-level javadocs
for more information on
org.springframework.asm
.
Convenient base class for self-autowiring classes that gets constructed within a Spring-based web application. Resolves
@Autowired
annotations in the endpoint class against beans in the current Spring root web application context (as determined by the current thread's context ClassLoader, which needs to be the web application's ClassLoader). Can alternatively be used as a delegate instead of as a base class.
A typical usage of this base class is a JAX-WS endpoint class: Such a Spring-based JAX-WS endpoint implementation will follow the standard JAX-WS contract for endpoint classes but will be 'thin' in that it delegates the actual work to one or more Spring-managed service beans - typically obtained using
@Autowired
. The lifecycle of such an endpoint instance will be managed by the JAX-WS runtime, hence the need for this base class to provide
@Autowired
processing based on the current Spring context.
NOTE: If there is an explicit way to access the ServletContext, prefer such a way over using this class. The WebApplicationContextUtils class allows for easy access to the Spring root web application context based on the ServletContext.
org.springframework.web.jsf.el.SpringBeanFacesELResolver
JSF
ELResolver
that delegates to the Spring root
WebApplicationContext
, resolving name references to Spring-defined beans.
Configure this resolver in your
faces-config.xml
file as follows:
<application> ... <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver> </application>
All your JSF expressions can then implicitly refer to the names of Spring-managed service layer beans, for example in property values of JSF-managed beans:
<managed-bean> <managed-bean-name>myJsfManagedBean</managed-bean-name> <managed-bean-class>example.MyJsfManagedBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> <managed-property> <property-name>mySpringManagedBusinessObject</property-name> <value>#{mySpringManagedBusinessObject}</value> </managed-property> </managed-bean>
with "mySpringManagedBusinessObject" defined as Spring bean in applicationContext.xml:
<bean id="mySpringManagedBusinessObject" class="example.MySpringManagedBusinessObject"> ... </bean>
org.springframework.scheduling.quartz.SpringBeanJobFactory
Subclass of AdaptableJobFactory that also supports Spring-style dependency injection on bean properties. This is essentially the direct equivalent of Spring's QuartzJobBean in the shape of a Quartz org.quartz.spi.JobFactory.
Applies scheduler context, job data map and trigger data map entries as bean property values. If no matching bean property is found, the entry is by default simply ignored. This is analogous to QuartzJobBean's behavior.
Compatible with Quartz 2.1.4 and higher, as of Spring 4.1.
org.springframework.web.servlet.view.tiles3.SpringBeanPreparerFactoryTiles org.apache.tiles.preparer.PreparerFactory implementation that expects preparer bean names and obtains preparer beans from the Spring ApplicationContext. The full bean creation process will be in the control of the Spring application context in this case, allowing for the use of scoped beans etc.
org.springframework.cglib.SpringCglibInfo
Empty class used to ensure that the
org.springframework.cglib
package is processed during javadoc generation.
See
package-level javadocs
for more information on
org.springframework.cglib
.
SpringClassRule
is a custom JUnit TestRule that supports
class-level
features of the
Spring TestContext Framework
in standard JUnit tests by means of the TestContextManager and associated support classes and annotations.
In contrast to the org.springframework.test.context.junit4.SpringJUnit4ClassRunner, Spring's rule-based JUnit support has the advantage that it is independent of any org.junit.runner.Runner and can therefore be combined with existing alternative runners like JUnit's
Parameterized
or third-party runners such as the
MockitoJUnitRunner
.
In order to achieve the same functionality as the
SpringJUnit4ClassRunner
, however, a
SpringClassRule
must be combined with a SpringMethodRule, since
SpringClassRule
only supports the class-level features of the
SpringJUnit4ClassRunner
.
public class ExampleSpringIntegrationTest { @ClassRule public static final SpringClassRule springClassRule = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); // ... }
The following list constitutes all annotations currently supported directly or indirectly by
SpringClassRule
.
(Note that additional annotations may be supported by various org.springframework.test.context.TestExecutionListener or org.springframework.test.context.TestContextBootstrapper implementations.)
NOTE: As of Spring Framework 4.3, this class requires JUnit 4.12 or higher.
org.springframework.web.socket.server.standard.SpringConfiguratorA javax.websocket.server.ServerEndpointConfig.Configurator for initializing ServerEndpoint-annotated classes through Spring.
@ServerEndpoint(value = "/echo", configurator = SpringConfigurator.class) public class EchoEndpoint { // ... }
org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory
JSR-303 ConstraintValidatorFactory implementation that delegates to a Spring BeanFactory for creating autowired ConstraintValidator instances.
Note that this class is meant for programmatic use, not for declarative use in a standard
validation.xml
file. Consider org.springframework.web.bind.support.SpringWebConstraintValidatorFactory for declarative use in a web application, e.g. with JAX-RS or JAX-WS.
JCA 1.7 javax.resource.spi.ResourceAdapter implementation that loads a Spring org.springframework.context.ApplicationContext, starting and stopping Spring-managed beans as part of the ResourceAdapter's lifecycle.
Ideal for application contexts that do not need any HTTP entry points but rather just consist of message endpoints and scheduled jobs etc. Beans in such a context may use application server resources such as the JTA transaction manager and JNDI-bound JDBC DataSources and JMS ConnectionFactory instances, and may also register with the platform's JMX server - all through Spring's standard transaction management and JNDI and JMX support facilities.
If the need for scheduling asynchronous work arises, consider using Spring's org.springframework.jca.work.WorkManagerTaskExecutor as a standard bean definition, to be injected into application beans through dependency injection. This WorkManagerTaskExecutor will automatically use the JCA WorkManager from the BootstrapContext that has been provided to this ResourceAdapter.
The JCA javax.resource.spi.BootstrapContext may also be accessed directly, through application components that implement the BootstrapContextAware interface. When deployed using this ResourceAdapter, the BootstrapContext is guaranteed to be passed on to such components.
This ResourceAdapter is to be defined in a "META-INF/ra.xml" file within a Java EE ".rar" deployment unit like as follows:
<?xml version="1.0" encoding="UTF-8"?> <connector xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/connector_1_5.xsd" version="1.5"> <vendor-name>Spring Framework</vendor-name> <eis-type>Spring Connector</eis-type> <resourceadapter-version>1.0</resourceadapter-version> <resourceadapter> <resourceadapter-class>org.springframework.jca.context.SpringContextResourceAdapter</resourceadapter-class> <config-property> <config-property-name>ContextConfigLocation</config-property-name> <config-property-type>java.lang.String</config-property-type> <config-property-value>META-INF/applicationContext.xml</config-property-value> </config-property> </resourceadapter> </connector>
Note that "META-INF/applicationContext.xml" is the default context config location, so it doesn't have to specified unless you intend to specify different/additional config files. So in the default case, you may remove the entire
config-property
section above.
For simple deployment needs, all you need to do is the following: Package all application classes into a RAR file (which is just a standard JAR file with a different file extension), add all required library jars into the root of the RAR archive, add a "META-INF/ra.xml" deployment descriptor as shown above as well as the corresponding Spring XML bean definition file(s) (typically "META-INF/applicationContext.xml"), and drop the resulting RAR file into your application server's deployment directory!
org.springframework.test.context.junit.jupiter.SpringExtension
SpringExtension
integrates the
Spring TestContext Framework
into JUnit 5's
Jupiter
programming model.
To use this extension, simply annotate a JUnit Jupiter based test class with
@ExtendWith(SpringExtension.class)
,
@SpringJUnitConfig
, or
@SpringJUnitWebConfig
.
General purpose factory loading mechanism for internal use within the framework.
SpringFactoriesLoader
loads
and instantiates factories of a given type from {@value #FACTORIES_RESOURCE_LOCATION} files which may be present in multiple JAR files in the classpath. The
spring.factories
file must be in Properties format, where the key is the fully qualified name of the interface or abstract class, and the value is a comma-separated list of implementation class names. For example:
example.MyService=example.MyServiceImpl1,example.MyServiceImpl2
where
example.MyService
is the name of the interface, and
MyServiceImpl1
and
MyServiceImpl2
are two implementations.
org.springframework.test.context.junit4.statements.SpringFailOnTimeout
SpringFailOnTimeout
is a custom JUnit Statement which adds support for Spring's org.springframework.test.annotation.Timed annotation by throwing an exception if the next statement in the execution chain takes more than the specified number of milliseconds.
In contrast to JUnit's org.junit.internal.runners.statements.FailOnTimeout, the next
statement
will be executed in the same thread as the caller and will therefore not be aborted preemptively.
Allows for creating Jackson (JsonSerializer, JsonDeserializer, KeyDeserializer, TypeResolverBuilder, TypeIdResolver) beans with autowiring against a Spring ApplicationContext.
As of Spring 4.3, this overrides all factory methods in HandlerInstantiator, including non-abstract ones and recently introduced ones from Jackson 2.4 and 2.5: for ValueInstantiator, ObjectIdGenerator, ObjectIdResolver, PropertyNamingStrategy, Converter, VirtualBeanPropertyWriter.
org.springframework.transaction.jta.SpringJtaSynchronizationAdapterAdapter that implements the JTA javax.transaction.Synchronization interface delegating to an underlying Spring org.springframework.transaction.support.TransactionSynchronization.
Useful for synchronizing Spring resource management code with plain JTA / EJB CMT transactions, despite the original code being built for Spring transaction synchronization.
org.springframework.web.servlet.view.tiles3.SpringLocaleResolverTiles LocaleResolver adapter that delegates to a Spring org.springframework.web.servlet.LocaleResolver, exposing the DispatcherServlet-managed locale.
This adapter gets automatically registered by TilesConfigurer.
org.springframework.test.context.junit4.rules.SpringMethodRule
SpringMethodRule
is a custom JUnit 4 MethodRule that supports instance-level and method-level features of the
Spring TestContext Framework
in standard JUnit tests by means of the TestContextManager and associated support classes and annotations.
In contrast to the org.springframework.test.context.junit4.SpringJUnit4ClassRunner, Spring's rule-based JUnit support has the advantage that it is independent of any org.junit.runner.Runner and can therefore be combined with existing alternative runners like JUnit's
Parameterized
or third-party runners such as the
MockitoJUnitRunner
.
In order to achieve the same functionality as the
SpringJUnit4ClassRunner
, however, a
SpringMethodRule
must be combined with a SpringClassRule, since
SpringMethodRule
only supports the instance-level and method-level features of the
SpringJUnit4ClassRunner
.
public class ExampleSpringIntegrationTest { @ClassRule public static final SpringClassRule springClassRule = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); // ... }
The following list constitutes all annotations currently supported directly or indirectly by
SpringMethodRule
.
(Note that additional annotations may be supported by various org.springframework.test.context.TestExecutionListener or org.springframework.test.context.TestContextBootstrapper implementations.)
NOTE: As of Spring Framework 4.3, this class requires JUnit 4.12 or higher.
WARNING:
Due to the shortcomings of JUnit rules, the
SpringMethodRule
does
not
support the
beforeTestExecution()
and
afterTestExecution()
callbacks of the org.springframework.test.context.TestExecutionListener API.
Custom extension of CGLIB's DefaultNamingPolicy, modifying the tag in generated class names from "ByCGLIB" to "BySpringCGLIB".
This is primarily designed to avoid clashes between a regular CGLIB version (used by some other library) and Spring's embedded variant, in case the same class happens to get proxied for different purposes.
org.springframework.test.context.junit4.SpringRunner
SpringRunner
is an
alias
for the SpringJUnit4ClassRunner.
To use this class, simply annotate a JUnit 4 based test class with
@RunWith(SpringRunner.class)
.
If you would like to use the Spring TestContext Framework with a runner other than this one, use org.springframework.test.context.junit4.rules.SpringClassRule and org.springframework.test.context.junit4.rules.SpringMethodRule.
NOTE: This class requires JUnit 4.12 or higher.
org.springframework.web.SpringServletContainerInitializer
Servlet 3.0 ServletContainerInitializer designed to support code-based configuration of the servlet container using Spring's WebApplicationInitializer SPI as opposed to (or possibly in combination with) the traditional
web.xml
-based approach. Mechanism of Operation This class will be loaded and instantiated and have its
#onStartup
method invoked by any Servlet 3.0-compliant container during container startup assuming that the
spring-web
module JAR is present on the classpath. This occurs through the JAR Services API
ServiceLoader#load(Class)
method detecting the
spring-web
module's
META-INF/services/javax.servlet.ServletContainerInitializer
service provider configuration file. See the
JAR Services API documentation
as well as section
8.2.4
of the Servlet 3.0 Final Draft specification for complete details. In combination with
web.xml
A web application can choose to limit the amount of classpath scanning the Servlet container does at startup either through the
metadata-complete
attribute in
web.xml
, which controls scanning for Servlet annotations or through an
<absolute-ordering>
element also in
web.xml
, which controls which web fragments (i.e. jars) are allowed to perform a
ServletContainerInitializer
scan. When using this feature, the SpringServletContainerInitializer can be enabled by adding "spring_web" to the list of named web fragments in
web.xml
as follows:
<absolute-ordering> <name>some_web_fragment</name> <name>spring_web</name> </absolute-ordering>
Relationship to Spring's
WebApplicationInitializer
Spring's
WebApplicationInitializer
SPI consists of just one method:
WebApplicationInitializer#onStartup(ServletContext)
. The signature is intentionally quite similar to
ServletContainerInitializer#onStartup(Set, ServletContext)
: simply put,
SpringServletContainerInitializer
is responsible for instantiating and delegating the
ServletContext
to any user-defined
WebApplicationInitializer
implementations. It is then the responsibility of each
WebApplicationInitializer
to do the actual work of initializing the
ServletContext
. The exact process of delegation is described in detail in the
onStartup
documentation below. General Notes In general, this class should be viewed as
supporting infrastructure
for the more important and user-facing
WebApplicationInitializer
SPI. Taking advantage of this container initializer is also completely
optional
: while it is true that this initializer will be loaded and invoked under all Servlet 3.0+ runtimes, it remains the user's choice whether to make any
WebApplicationInitializer
implementations available on the classpath. If no
WebApplicationInitializer
types are detected, this container initializer will have no effect.
Note that use of this container initializer and of
WebApplicationInitializer
is not in any way "tied" to Spring MVC other than the fact that the types are shipped in the
spring-web
module JAR. Rather, they can be considered general-purpose in their ability to facilitate convenient code-based configuration of the
ServletContext
. In other words, any servlet, listener, or filter may be registered within a
WebApplicationInitializer
, not just Spring MVC-specific components.
This class is neither designed for extension nor intended to be extended. It should be considered an internal type, with
WebApplicationInitializer
being the public-facing SPI.
Implementation of Hibernate 3.1's CurrentSessionContext interface that delegates to Spring's SessionFactoryUtils for providing a Spring-managed current Session.
This CurrentSessionContext implementation can also be specified in custom SessionFactory setup through the "hibernate.current_session_context_class" property, with the fully qualified name of this class as value.
org.springframework.core.SpringVersionClass that exposes the Spring version. Fetches the "Implementation-Version" manifest attribute from the jar file.
Note that some ClassLoaders do not expose the package metadata, hence this class might not be able to determine the Spring version in all environments. Consider using a reflection-based check instead: For example, checking for the presence of a specific Spring 2.0 method that you intend to call.
org.springframework.web.bind.support.SpringWebConstraintValidatorFactoryJSR-303 ConstraintValidatorFactory implementation that delegates to the current Spring WebApplicationContext for creating autowired ConstraintValidator instances.
In contrast to org.springframework.validation.beanvalidation.SpringConstraintValidatorFactory, this variant is meant for declarative use in a standard
validation.xml
file, e.g. in combination with JAX-RS or JAX-WS.
@Sql
is used to annotate a test class or test method to configure SQL
#scripts
and
#statements
to be executed against a given database during integration tests.
Method-level declarations override class-level declarations.
Script execution is performed by the SqlScriptsTestExecutionListener, which is enabled by default.
The configuration options provided by this annotation and SqlConfig are equivalent to those supported by org.springframework.jdbc.datasource.init.ScriptUtils and org.springframework.jdbc.datasource.init.ResourceDatabasePopulator but are a superset of those provided by the
<jdbc:initialize-database/>
XML namespace element. Consult the javadocs of individual attributes in this annotation and SqlConfig for details.
Beginning with Java 8,
@Sql
can be used as a
Repeatable
annotation. Otherwise, SqlGroup can be used as an explicit container for declaring multiple instances of
@Sql
.
This annotation may be used as a meta-annotation to create custom composed annotations with attribute overrides.
org.springframework.jdbc.object.SqlFunctionSQL "function" wrapper for a query that returns a single row of results. The default behavior is to return an int, but that can be overridden by using the constructor with an extra return type parameter.
Intended to use to call SQL functions that return a single result using a query like "select user()" or "select sysdate from dual". It is not intended for calling more complex stored functions or for using a CallableStatement to invoke a stored procedure or stored function. Use StoredProcedure or SqlCall for this type of processing.
This is a concrete class, which there is often no need to subclass. Code using this package can create an object of this type, declaring SQL and parameters, and then invoke the appropriate
run
method repeatedly to execute the function. Subclasses are only supposed to add specialized
run
methods for specific parameter and return types.
Like all RdbmsOperation objects, SqlFunction objects are thread-safe.
org.springframework.test.context.jdbc.SqlGroupContainer annotation that aggregates several Sql annotations.
Can be used natively, declaring several nested
@Sql
annotations. Can also be used in conjunction with Java 8's support for repeatable annotations, where
@Sql
can simply be declared several times on the same class or method, implicitly generating this container annotation.
This annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.jdbc.core.SqlInOutParameter
Subclass of SqlOutParameter to represent an INOUT parameter. Will return
true
for SqlParameter's
#isInputValueProvided
test, in contrast to a standard SqlOutParameter.
Output parameters - like all stored procedure parameters - must have names.
org.springframework.jdbc.core.support.SqlLobValueObject to represent an SQL BLOB/CLOB value parameter. BLOBs can either be an InputStream or a byte array. CLOBs can be in the form of a Reader, InputStream or String. Each CLOB/BLOB value will be stored together with its length. The type is based on which constructor is used. Objects of this class are immutable except for the LobCreator reference. Use them and discard them.
This class holds a reference to a LocCreator that must be closed after the update has completed. This is done via a call to the closeLobCreator method. All handling of the LobCreator is done by the framework classes that use it - no need to set or close the LobCreator for end users of this class.
A usage example:
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); // reusable object LobHandler lobHandler = new DefaultLobHandler(); // reusable object jdbcTemplate.update( "INSERT INTO imagedb (image_name, content, description) VALUES (?, ?, ?)", new Object[] { name, new SqlLobValue(contentStream, contentLength, lobHandler), new SqlLobValue(description, lobHandler) }, new int[] {Types.VARCHAR, Types.BLOB, Types.CLOB});
org.springframework.jdbc.core.SqlOutParameter
Subclass of SqlParameter to represent an output parameter. No additional properties: instanceof will be used to check for such types.
Output parameters - like all stored procedure parameters - must have names.
org.springframework.jdbc.core.SqlParameterValueObject to represent a SQL parameter value, including parameter metadata such as the SQL type and the scale for numeric values.
Designed for use with JdbcTemplate's operations that take an array of argument values: Each such argument value may be a
SqlParameterValue
, indicating the SQL type (and optionally the scale) instead of letting the template guess a default type. Note that this only applies to the operations with a 'plain' argument array, not to the overloaded variants with an explicit type array.
Interface to be implemented by objects that can provide SQL strings.
Typically implemented by PreparedStatementCreators, CallableStatementCreators and StatementCallbacks that want to expose the SQL they use to create their statements, to allow for better contextual information in case of exceptions.
org.springframework.jdbc.core.SqlReturnUpdateCountRepresents a returned update count from a stored procedure call.
Returned update counts - like all stored procedure parameters - must have names.
org.springframework.jdbc.core.SqlRowSetResultSetExtractorResultSetExtractor implementation that returns a Spring SqlRowSet representation for each given ResultSet.
The default implementation uses a standard JDBC CachedRowSet underneath.
org.springframework.jdbc.support.incrementer.SqlServerMaxValueIncrementerDataFieldMaxValueIncrementer that increments the maximum value of a given SQL Server table with the equivalent of an auto-increment column. Note: If you use this class, your table key column should NOT be defined as an IDENTITY column, as the sequence table does the job.
This class is intended to be used with Microsoft SQL Server.
The sequence is kept in a table. There should be one sequence table per table that needs an auto-generated key.
Example:
create table tab (id int not null primary key, text varchar(100)) create table tab_sequence (id bigint identity) insert into tab_sequence default values
If "cacheSize" is set, the intermediate values are served without querying the database. If the server or your application is stopped or crashes or a transaction is rolled back, the unused values will never be served. The maximum hole size in numbering is consequently the value of cacheSize.
HINT:
Since Microsoft SQL Server supports the JDBC 3.0
getGeneratedKeys
method, it is recommended to use IDENTITY columns directly in the tables and then using a org.springframework.jdbc.core.simple.SimpleJdbcInsert or utilizing a org.springframework.jdbc.support.KeyHolder when calling the with the
update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder)
method of the org.springframework.jdbc.core.JdbcTemplate.
Thanks to Preben Nilsson for the suggestion!
org.springframework.jdbc.support.SqlValueSimple interface for complex types to be set as statement parameters.
Implementations perform the actual work of setting the actual values. They must implement the callback method
setValue
which can throw SQLExceptions that will be caught and translated by the calling code. This callback method has access to the underlying Connection via the given PreparedStatement object, if that should be needed to create any database-specific objects.
Abstraction for handling XML object mapping to fields in a database.
Provides accessor methods for XML fields unmarshalled to an Object, and acts as factory for SqlXmlValue instances for marshalling purposes.
org.springframework.jms.listener.endpoint.StandardJmsActivationSpecFactoryStandard implementation of the JmsActivationSpecFactory interface. Supports the standard JMS properties as defined by the JMS 1.5 specification (Appendix B); ignores Spring's "maxConcurrency" and "prefetchSize" settings.
The 'activationSpecClass' property is required, explicitly defining the fully-qualified class name of the provider's ActivationSpec class (e.g. "org.apache.activemq.ra.ActiveMQActivationSpec").
Check out DefaultJmsActivationSpecFactory for an extended variant of this class, supporting some further default conventions beyond the plain JMS 1.5 specification.
org.springframework.scripting.support.StandardScriptEvalException
Exception decorating a javax.script.ScriptException coming out of JSR-223 script evaluation, i.e. a
javax.script.ScriptEngine#eval
call or
javax.script.Invocable#invokeMethod
/
javax.script.Invocable#invokeFunction
call.
This exception does not print the Java stacktrace, since the JSR-223 ScriptException results in a rather convoluted text output. From that perspective, this exception is primarily a decorator for a ScriptException root cause passed into an outer exception.
org.springframework.scripting.support.StandardScriptFactoryorg.springframework.scripting.ScriptFactory implementation based on the JSR-223 script engine abstraction (as included in Java 6+). Supports JavaScript, Groovy, JRuby and other JSR-223 compliant engines.
Typically used in combination with a org.springframework.scripting.support.ScriptFactoryPostProcessor; see the latter's javadoc for a configuration example.
org.springframework.web.context.request.async.StandardServletAsyncWebRequestA Servlet 3.0 implementation of AsyncWebRequest.
The servlet and all filters involved in an async request must have async support enabled using the Servlet API or by adding an
<async-supported>true</async-supported>
element to servlet and filter declarations in
web.xml
.
Environment implementation to be used by
Servlet
-based web applications. All web-related (servlet-based)
ApplicationContext
classes initialize an instance by default.
Contributes
ServletConfig
,
ServletContext
, and JNDI-based PropertySource instances. See
#customizePropertySources
method documentation for details.
Standard implementation of the MultipartResolver interface, based on the Servlet 3.0 javax.servlet.http.Part API. To be added as "multipartResolver" bean to a Spring DispatcherServlet context, without any extra configuration at the bean level (see below).
Note:
In order to use Servlet 3.0 based multipart parsing, you need to mark the affected servlet with a "multipart-config" section in
web.xml
, or with a javax.servlet.MultipartConfigElement in programmatic servlet registration, or (in case of a custom servlet class) possibly with a javax.servlet.annotation.MultipartConfig annotation on your servlet class. Configuration settings such as maximum sizes or storage locations need to be applied at that servlet registration level; Servlet 3.0 does not allow for them to be set at the MultipartResolver level.
Utility methods for PreparedStatementSetter/Creator and CallableStatementCreator implementations, providing sophisticated parameter management (including support for LOB values).
Used by PreparedStatementCreatorFactory and CallableStatementCreatorFactory, but also available for direct use in custom setter/creator implementations.
org.springframework.beans.factory.support.StaticListableBeanFactoryStatic org.springframework.beans.factory.BeanFactory implementation which allows to register existing singleton instances programmatically. Does not have support for prototype beans or aliases.
Serves as example for a simple implementation of the org.springframework.beans.factory.ListableBeanFactory interface, managing existing bean instances rather than creating new ones based on bean definitions, and not implementing any extended SPI interfaces (such as org.springframework.beans.factory.config.ConfigurableBeanFactory).
For a full-fledged factory based on bean definitions, have a look at DefaultListableBeanFactory.
org.springframework.context.support.StaticMessageSourceSimple implementation of org.springframework.context.MessageSource which allows messages to be registered programmatically. This MessageSource supports basic internationalization.
Intended for testing rather than for use in production systems.
org.springframework.web.context.support.StaticWebApplicationContextStatic org.springframework.web.context.WebApplicationContext implementation for testing. Not intended for use in production applications.
Implements the org.springframework.web.context.ConfigurableWebApplicationContext interface to allow for direct replacement of an XmlWebApplicationContext, despite not actually supporting external configuration files.
Interprets resource paths as servlet context resources, i.e. as paths beneath the web application root. Absolute paths, e.g. for files outside the web app root, can be accessed via "file:" URLs, as implemented by org.springframework.core.io.DefaultResourceLoader.
In addition to the special beans detected by org.springframework.context.support.AbstractApplicationContext, this class detects a bean of type org.springframework.ui.context.ThemeSource in the context, under the special bean name "themeSource".
org.springframework.test.web.servlet.result.StatusResultMatchersFactory for assertions on the response status.
An instance of this class is typically accessed via
MockMvcResultMatchers#status
.
Convenience methods for working with the StAX API. Partly historic due to JAXP 1.3 compatibility; as of Spring 4.0, relying on JAXP 1.4 as included in JDK 1.6 and higher.
In particular, methods for using StAX (
javax.xml.stream
) in combination with the TrAX API (
javax.xml.transform
), and converting StAX readers/writers into SAX readers/handlers and vice-versa.
Base class for STOMP client implementations.
Subclasses can connect over WebSocket or TCP using any library. When creating a new connection, a subclass can create an instance of @link DefaultStompSession} which extends org.springframework.messaging.tcp.TcpConnectionHandler whose lifecycle methods the subclass must then invoke.
In effect,
TcpConnectionHandler
and
TcpConnection
are the contracts that any subclass must adapt to while using StompEncoder and StompDecoder to encode and decode STOMP messages.
Decodes one or more STOMP frames contained in a ByteBuffer.
An attempt is made to read all complete STOMP frames from the buffer, which could be zero, one, or more. If there is any left-over content, i.e. an incomplete STOMP frame, at the end the buffer is reset to point to the beginning of the partial content. The caller is then responsible for dealing with that incomplete content by buffering until there is more input available.
org.springframework.messaging.simp.stomp.StompHeaderAccessor
A
MessageHeaderAccessor
to use when creating a
Message
from a decoded STOMP frame, or when encoding a
Message
to a STOMP frame.
When created from STOMP frame content, the actual STOMP headers are stored in the native header sub-map managed by the parent class org.springframework.messaging.support.NativeMessageHeaderAccessor while the parent class SimpMessageHeaderAccessor manages common processing headers some of which are based on STOMP headers (e.g. destination, content-type, etc).
An instance of this class can also be created by wrapping an existing
Message
. That message may have been created with the more generic org.springframework.messaging.simp.SimpMessageHeaderAccessor in which case STOMP headers are created from common processing headers. In this case it is also necessary to invoke either
#updateStompCommandAsClientMessage()
or
#updateStompCommandAsServerMessage()
if sending a message and depending on whether a message is sent to a client or the message broker.
Simple stop watch, allowing for timing of a number of tasks, exposing total running time and running time for each named task.
Conceals use of
System.currentTimeMillis()
, improving the readability of application code and reducing the likelihood of calculation errors.
Note that this object is not designed to be thread-safe and does not use synchronization.
This class is normally used to verify performance during proof-of-concepts and in development, rather than as part of production applications.
org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
A controller method return value type for asynchronous request processing where the application can write directly to the response
OutputStream
without holding up the Servlet container thread.
Note:
when using this option it is highly recommended to configure explicitly the TaskExecutor used in Spring MVC for executing asynchronous requests. Both the MVC Java config and the MVC namespaces provide options to configure asynchronous handling. If not using those, an application can set the
taskExecutor
property of org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.
Supports return values of type org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody and also
ResponseEntity<StreamingResponseBody>
.
Custom java.beans.PropertyEditor for String arrays.
Strings must be in CSV format, with a customizable separator. By default values in the result are trimmed of whitespace.
org.springframework.core.codec.StringDecoder
Decode from a bytes stream to a
String
stream.
By default, this decoder will split the received DataBuffers along newline characters (
\r\n
), but this can be changed by passing
false
as a constructor argument.
Custom java.beans.PropertyEditor for converting MultipartFile to Strings.
Allows one to specify the charset to use.
org.springframework.beans.propertyeditors.StringTrimmerEditorProperty editor that trims Strings.
Optionally allows transforming an empty string into a
null
value. Needs to be explicitly registered, e.g. for command binding.
Simple utility class to allow for convenient access to value styling logic, mainly to support descriptive logging messages.
For more sophisticated needs, use the ValueStyler abstraction directly. This class simply uses a shared DefaultValueStyler instance underneath.
org.springframework.web.socket.messaging.SubProtocolHandlerA contract for handling WebSocket messages as part of a higher level protocol, referred to as "sub-protocol" in the WebSocket RFC specification. Handles both WebSocketMessages from a client as well as Messages to a client.
Implementations of this interface can be configured on a SubProtocolWebSocketHandler which selects a sub-protocol handler to delegate messages to based on the sub-protocol requested by the client through the
Sec-WebSocket-Protocol
request header.
Annotation for mapping subscription messages onto specific handler methods based on the destination of a subscription. Supported with STOMP over WebSocket only (e.g. STOMP SUBSCRIBE frame).
This is a method-level annotation that can be combined with a type-level org.springframework.messaging.handler.annotation.MessageMapping.
Supports the same method arguments as
@MessageMapping
; however, subscription messages typically do not have a body.
The return value also follows the same rules as for
@MessageMapping
, except if the method is not annotated with org.springframework.messaging.handler.annotation.SendTo or SendToUser, the message is sent directly back to the connected user and does not pass through the message broker. This is useful for implementing a request-reply pattern.
NOTE:
When using controller interfaces (e.g. for AOP proxying), make sure to consistently put
all
your mapping annotations - such as
@MessageMapping
and
@SubscribeMapping
- on the controller
interface
rather than on the implementation class.
HandlerMethodReturnValueHandler
for replying directly to a subscription. It is supported on methods annotated with org.springframework.messaging.simp.annotation.SubscribeMapping such that the return value is treated as a response to be sent directly back on the session. This allows a client to implement a request-response pattern and use it for example to obtain some data upon initialization.
The value returned from the method is converted and turned into a Message that is then enriched with the sessionId, subscriptionId, and destination of the input message.
Note:
this default behavior for interpreting the return value from an
@SubscribeMapping
method can be overridden through use of the SendTo or SendToUser annotations in which case a message is prepared and sent to the broker instead.
DataFieldMaxValueIncrementer that increments the maximum value of a given Sybase SQL Anywhere table with the equivalent of an auto-increment column. Note: If you use this class, your table key column should NOT be defined as an IDENTITY column, as the sequence table does the job.
This class is intended to be used with Sybase Anywhere.
The sequence is kept in a table. There should be one sequence table per table that needs an auto-generated key.
Example:
create table tab (id int not null primary key, text varchar(100)) create table tab_sequence (id bigint identity) insert into tab_sequence values(DEFAULT)
If "cacheSize" is set, the intermediate values are served without querying the database. If the server or your application is stopped or crashes or a transaction is rolled back, the unused values will never be served. The maximum hole size in numbering is consequently the value of cacheSize.
HINT:
Since Sybase Anywhere supports the JDBC 3.0
getGeneratedKeys
method, it is recommended to use IDENTITY columns directly in the tables and then using a org.springframework.jdbc.core.simple.SimpleJdbcInsert or utilizing a org.springframework.jdbc.support.KeyHolder when calling the with the
update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder)
method of the org.springframework.jdbc.core.JdbcTemplate.
Thanks to Tarald Saxi Stormark for the suggestion!
org.springframework.jdbc.support.incrementer.SybaseMaxValueIncrementerDataFieldMaxValueIncrementer that increments the maximum value of a given Sybase table with the equivalent of an auto-increment column. Note: If you use this class, your table key column should NOT be defined as an IDENTITY column, as the sequence table does the job.
This class is intended to be used with Sybase Adaptive Server.
The sequence is kept in a table. There should be one sequence table per table that needs an auto-generated key.
Example:
create table tab (id int not null primary key, text varchar(100)) create table tab_sequence (id bigint identity) insert into tab_sequence values()
If "cacheSize" is set, the intermediate values are served without querying the database. If the server or your application is stopped or crashes or a transaction is rolled back, the unused values will never be served. The maximum hole size in numbering is consequently the value of cacheSize.
HINT:
Since Sybase supports the JDBC 3.0
getGeneratedKeys
method, it is recommended to use IDENTITY columns directly in the tables and then using a org.springframework.jdbc.core.simple.SimpleJdbcInsert or utilizing a org.springframework.jdbc.support.KeyHolder when calling the with the
update(PreparedStatementCreator psc, KeyHolder generatedKeyHolder)
method of the org.springframework.jdbc.core.JdbcTemplate.
Thanks to Yinwei Liu for the suggestion!
org.springframework.core.task.SyncTaskExecutorTaskExecutor implementation that executes each task synchronously in the calling thread.
Mainly intended for testing scenarios.
Execution in the calling thread does have the advantage of participating in it's thread context, for example the thread context class loader or the thread's current transaction association. That said, in many cases, asynchronous execution will be preferable: choose an asynchronous
TaskExecutor
instead for such scenarios.
HttpMessageReader
for parsing
"multipart/form-data"
requests to a stream of Part's using the Synchronoss NIO Multipart library.
This reader can be provided to MultipartHttpMessageReader in order to aggregate all parts into a Map.
org.springframework.core.annotation.SynthesizedAnnotationMarker interface implemented by synthesized annotation proxies.
Used to detect whether an annotation has already been synthesized.
org.springframework.core.env.SystemEnvironmentPropertySourceSpecialization of MapPropertySource designed for use with system environment variables . Compensates for constraints in Bash and other shells that do not allow for variables containing the period character and/or hyphen character; also allows for uppercase variations on property names for more idiomatic shell use.
For example, a call to
getProperty("foo.bar")
will attempt to find a value for the original property or any 'equivalent' property, returning the first found:
foo.bar
- the original name
foo_bar
- with underscores for periods (if any)
FOO.BAR
- original, with upper case
FOO_BAR
- with underscores and upper case
The same applies for calls to
#containsProperty(String)
, which returns
true
if any of the above properties are present, otherwise
false
.
This feature is particularly useful when specifying active or default profiles as environment variables. The following is not allowable under Bash:
spring.profiles.active=p1 java -classpath ... MyApp
However, the following syntax is permitted and is also more conventional:
SPRING_PROFILES_ACTIVE=p1 java -classpath ... MyApp
Enable debug- or trace-level logging for this class (or package) for messages explaining when these 'property name resolutions' occur.
This property source is included by default in StandardEnvironment and all its subclasses.
org.springframework.util.SystemPropertyUtilsHelper class for resolving placeholders in texts. Usually applied to file paths.
A text may contain
${...}
placeholders, to be resolved as system properties: e.g.
${user.dir}
. Default values can be supplied using the ":" separator between key and value.
Utility class for tag library related code, exposing functionality such as translating String to web scopes.
page
will be transformed to
PageContext.PAGE_SCOPE
request
will be transformed to
PageContext.REQUEST_SCOPE
session
will be transformed to
PageContext.SESSION_SCOPE
application
will be transformed to
PageContext.APPLICATION_SCOPE
Utility methods for decorating tasks with error handling.
NOTE: This class is intended for internal use by Spring's scheduler implementations. It is only public so that it may be accessed from impl classes within other packages. It is not intended for general use.
org.springframework.jdbc.support.lob.TemporaryLobCreator
LobCreator implementation based on temporary LOBs, using JDBC 4.0's
java.sql.Connection#createBlob()
/
java.sql.Connection#createClob()
mechanism.
Used by DefaultLobHandler's
DefaultLobHandler#setCreateTemporaryLob
mode. Can also be used directly to reuse the tracking and freeing of temporary LOBs.
Utility methods for working with transactions and data access related beans within the Spring TestContext Framework .
Mainly for internal use within the framework.
org.springframework.test.context.TestExecutionListener
TestExecutionListener
defines a
listener
API for reacting to test execution events published by the TestContextManager with which the listener is registered.
Note that not all testing frameworks support all lifecycle callbacks defined in this API. For example,
#beforeTestExecution
and
#afterTestExecution
are not supported in conjunction with JUnit 4 when using the org.springframework.test.context.junit4.rules.SpringMethodRule.
This interface provides empty
default
implementations for all methods. Concrete implementations can therefore choose to override only those methods suitable for the task at hand.
Concrete implementations must provide a
public
no-args constructor, so that listeners can be instantiated transparently by tools and configuration mechanisms.
Implementations may optionally declare the position in which they should be ordered among the chain of default listeners via the org.springframework.core.Ordered interface or org.springframework.core.annotation.Order annotation. See
TestContextBootstrapper#getTestExecutionListeners()
for details.
Spring provides the following out-of-the-box implementations (all of which implement
Ordered
):
Utility methods for working with TestPropertySource and adding test PropertySource to the
Environment
.
Primarily intended for use within the framework.
org.springframework.test.context.transaction.TestTransaction
TestTransaction
provides a collection of static utility methods for programmatic interaction with
test-managed transactions
within
test
methods,
before
methods, and
after
methods.
Consult the javadocs for TransactionalTestExecutionListener for a detailed explanation of test-managed transactions .
Support for
TestTransaction
is automatically available whenever the
TransactionalTestExecutionListener
is enabled. Note that the
TransactionalTestExecutionListener
is typically enabled by default, but it can also be manually enabled via the TestExecutionListeners annotation.
A convenient base class for WebSocketHandler implementations that process text messages only.
Binary messages are rejected with
CloseStatus#NOT_ACCEPTABLE
. All other methods have empty implementations.
The
<textarea>
tag renders an HTML 'textarea'.
Attribute Summary Attribute Required? Runtime Expression? Description
accesskey
false
HTML Standard Attribute
false
HTML Required Attribute
cssClass
false
HTML Optional Attribute
cssErrorClass
false
HTML Optional Attribute. Used when the bound field has errors.
cssStyle
false
HTML Optional Attribute
false
HTML Standard Attribute
disabled
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will disable the HTML element.
htmlEscape
false
Enable/disable HTML escaping of rendered values.
false
HTML Standard Attribute
false
HTML Standard Attribute
onblur
false
HTML Event Attribute
onchange
false
HTML Event Attribute
onclick
false
HTML Event Attribute
ondblclick
false
HTML Event Attribute
onfocus
false
HTML Event Attribute
onkeydown
false
HTML Event Attribute
onkeypress
false
HTML Event Attribute
onkeyup
false
HTML Event Attribute
onmousedown
false
HTML Event Attribute
onmousemove
false
HTML Event Attribute
onmouseout
false
HTML Event Attribute
onmouseover
false
HTML Event Attribute
onmouseup
false
HTML Event Attribute
onselect
false
HTML Event Attribute
Path to property for data binding
readonly
false
HTML Optional Attribute. Setting the value of this attribute to 'true' will make the HTML element readonly.
false
HTML Required Attribute
tabindex
false
HTML Standard Attribute
title
false
HTML Standard Attribute
org.springframework.web.servlet.tags.ThemeTag
The
<theme>
tag looks up a theme message in the scope of this page. Messages are looked up using the ApplicationContext's ThemeSource, and thus should support internationalization.
Regards a HTML escaping setting, either on this tag instance, the page level, or the web.xml level.
If "code" isn't set or cannot be resolved, "text" will be used as default message.
Message arguments can be specified via the
arguments
attribute or by using nested
<spring:argument>
tags.
Alternative to an object pool. This org.springframework.aop.TargetSource uses a threading model in which every thread has its own copy of the target. There's no contention for targets. Target object creation is kept to a minimum on the running server.
Application code is written as to a normal pool; callers can't assume they will be dealing with the same instance in invocations in different threads. However, state can be relied on during the operations of a single thread: for example, if one caller makes repeated calls on the AOP proxy.
Cleanup of thread-bound objects is performed on BeanFactory destruction, calling their
DisposableBean.destroy()
method if available. Be aware that many thread-bound objects can be around until the application actually shuts down.
JavaBean that allows for configuring a java.util.concurrent.ThreadPoolExecutor in bean style (through its "corePoolSize", "maxPoolSize", "keepAliveSeconds", "queueCapacity" properties) and exposing it as a bean reference of its native java.util.concurrent.ExecutorService type.
For an alternative, you may set up a ThreadPoolExecutor instance directly using constructor injection, or use a factory method definition that points to the java.util.concurrent.Executors class.
This is strongly recommended in particular for common
@Bean
methods in configuration classes, where this
FactoryBean
variant would force you to return the
FactoryBean
type instead of the actual
Executor
type.
If you need a timing-based java.util.concurrent.ScheduledExecutorService instead, consider ScheduledExecutorFactoryBean.
Tag interface for throws advice.
There are not any methods on this interface, as methods are invoked by reflection. Implementing classes must implement methods of the form:
void afterThrowing([Method, args, target], ThrowableSubclass);
Some examples of valid methods would be:
public void afterThrowing(Exception ex)
public void afterThrowing(RemoteException)
public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)
The first three arguments are optional, and only useful if we want further information about the joinpoint, as in AspectJ
after-throwing
advice.
Note: If a throws-advice method throws an exception itself, it will override the original exception (i.e. change the exception thrown to the user). The overriding exception will typically be a RuntimeException; this is compatible with any method signature. However, if a throws-advice method throws a checked exception, it will have to match the declared exceptions of the target method and is hence to some degree coupled to specific target method signatures. Do not throw an undeclared checked exception that is incompatible with the target method's signature!
org.springframework.aop.framework.adapter.ThrowsAdviceInterceptorInterceptor to wrap an after-throwing advice.
The signatures on handler methods on the
ThrowsAdvice
implementation method argument must be of the form:
void afterThrowing([Method, args, target], ThrowableSubclass);
Only the last argument is required.
Some examples of valid methods would be:
public void afterThrowing(Exception ex)
public void afterThrowing(RemoteException)
public void afterThrowing(Method method, Object[] args, Object target, Exception ex)
public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)
This is a framework class that need not be used directly by Spring users.
org.springframework.web.servlet.view.tiles3.TilesConfigurerHelper class to configure Tiles 3.x for the Spring Framework. See http://tiles.apache.org for more information about Tiles, which basically is a templating mechanism for web applications using JSPs and other template engines.
The TilesConfigurer simply configures a TilesContainer using a set of files containing definitions, to be accessed by TilesView instances. This is a Spring-based alternative (for usage in Spring configuration) to the Tiles-provided
ServletContextListener
(e.g. org.apache.tiles.extras.complete.CompleteAutoloadTilesListener for usage in
web.xml
.
TilesViews can be managed by any org.springframework.web.servlet.ViewResolver. For simple convention-based view resolution, consider using TilesViewResolver.
A typical TilesConfigurer bean definition looks as follows:
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/defs/general.xml</value> <value>/WEB-INF/defs/widgets.xml</value> <value>/WEB-INF/defs/administrator.xml</value> <value>/WEB-INF/defs/customer.xml</value> <value>/WEB-INF/defs/templates.xml</value> </list> </property> </bean>
The values in the list are the actual Tiles XML files containing the definitions. If the list is not specified, the default is
"/WEB-INF/tiles.xml"
.
Note that in Tiles 3 an underscore in the name of a file containing Tiles definitions is used to indicate locale information, for example:
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer"> <property name="definitions"> <list> <value>/WEB-INF/defs/tiles.xml</value> <value>/WEB-INF/defs/tiles_fr_FR.xml</value> </list> </property> </bean>
org.springframework.test.annotation.Timed
Test-specific annotation to indicate that a test method has to finish execution in a specified time period .
If the text execution takes longer than the specified time period, then the test is considered to have failed.
Note that the time period includes execution of the test method itself, any Repeat of the test, and any set up or tear down of the test fixture.
As of Spring Framework 4.0, this annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.web.context.request.async.TimeoutCallableProcessingInterceptorSends a 503 (SERVICE_UNAVAILABLE) in case of a timeout if the response is not already committed. As of 4.2.8 this is done indirectly by setting the result to an AsyncRequestTimeoutException which is then handled by Spring MVC's default exception handling as a 503 error.
Registered at the end, after all other interceptors and therefore invoked only if no other interceptor handles the timeout.
Note that according to RFC 7231, a 503 without a 'Retry-After' header is interpreted as a 500 error and the client should not retry. Applications can install their own interceptor to handle a timeout and add a 'Retry-After' header if necessary.
org.springframework.web.context.request.async.TimeoutDeferredResultProcessingInterceptorSends a 503 (SERVICE_UNAVAILABLE) in case of a timeout if the response is not already committed. As of 4.2.8 this is done indirectly by returning AsyncRequestTimeoutException as the result of processing which is then handled by Spring MVC's default exception handling as a 503 error.
Registered at the end, after all other interceptors and therefore invoked only if no other interceptor handles the timeout.
Note that according to RFC 7231, a 503 without a 'Retry-After' header is interpreted as a 500 error and the client should not retry. Applications can install their own interceptor to handle a timeout and add a 'Retry-After' header if necessary.
org.springframework.scheduling.commonj.TimerManagerFactoryBeanorg.springframework.beans.factory.FactoryBean that retrieves a CommonJ commonj.timers.TimerManager and exposes it for bean references.
This is the central convenience class for setting up a CommonJ TimerManager in a Spring context.
Allows for registration of ScheduledTimerListeners. This is the main purpose of this class; the TimerManager itself could also be fetched from JNDI via org.springframework.jndi.JndiObjectFactoryBean. In scenarios that just require static registration of tasks at startup, there is no need to access the TimerManager itself in application code.
Note that the TimerManager uses a TimerListener instance that is shared between repeated executions, in contrast to Quartz which instantiates a new Job for each execution.
org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy
A WebSocket
RequestUpgradeStrategy
for Apache Tomcat. Compatible with all versions of Tomcat that support JSR-356, i.e. Tomcat 7.0.47+ and higher.
To modify properties of the underlying javax.websocket.server.ServerContainer you can use ServletServerContainerFactoryBean in XML configuration or, when using Java configuration, access the container instance through the "javax.websocket.server.ServerContainer" ServletContext attribute.
org.springframework.transaction.interceptor.TransactionAttributeEditorPropertyEditor for TransactionAttribute objects. Accepts a String of form
PROPAGATION_NAME, ISOLATION_NAME, readOnly, timeout_NNNN,+Exception1,-Exception2
where only propagation code is required. For example:
PROPAGATION_MANDATORY, ISOLATION_DEFAULT
The tokens can be in any order. Propagation and isolation codes must use the names of the constants in the TransactionDefinition class. Timeout values are in seconds. If no timeout is specified, the transaction manager will apply a default timeout specific to the particular transaction manager.
A "+" before an exception name substring indicates that transactions should commit even if this exception is thrown; a "-" that they should roll back.
org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisorAdvisor driven by a TransactionAttributeSource, used to include a TransactionInterceptor only for methods that are transactional.
Because the AOP framework caches advice calculations, this is normally faster than just letting the TransactionInterceptor run and find out itself that it has no work to do.
org.springframework.transaction.interceptor.TransactionAttributeSourceEditorProperty editor that converts a String into a TransactionAttributeSource. The transaction attribute string must be parseable by the TransactionAttributeEditor in this package.
Strings are in property syntax, with the form:
FQCN.methodName=<transaction attribute string>
For example:
com.mycompany.mycode.MyClass.myMethod=PROPAGATION_MANDATORY,ISOLATION_DEFAULT
NOTE: The specified class must be the one where the methods are defined; in case of implementing an interface, the interface class name.
Note: Will register all overloaded methods for a given name. Does not support explicit registration of certain overloaded methods. Supports "xxx*" mappings, e.g. "notify*" for "notify" and "notifyAll".
org.springframework.cache.transaction.TransactionAwareCacheDecorator
Cache decorator which synchronizes its
#put
,
#evict
and
#clear
operations with Spring-managed transactions (through Spring's TransactionSynchronizationManager, performing the actual cache put/evict/clear operation only in the after-commit phase of a successful transaction. If no transaction is active,
#put
,
#evict
and
#clear
operations will be performed immediately, as usual.
Use of more aggressive operations such as
#putIfAbsent
cannot be deferred to the after-commit phase of a running transaction. Use these with care.
Proxy for a target CacheManager, exposing transaction-aware Cache objects which synchronize their
Cache#put
operations with Spring-managed transactions (through Spring's org.springframework.transaction.support.TransactionSynchronizationManager, performing the actual cache put operation only in the after-commit phase of a successful transaction. If no transaction is active,
Cache#put
operations will be performed immediately, as usual.
Proxy for a target JMS javax.jms.ConnectionFactory, adding awareness of Spring-managed transactions. Similar to a transactional JNDI ConnectionFactory as provided by a Java EE application server.
Messaging code which should remain unaware of Spring's JMS support can work with this proxy to seamlessly participate in Spring-managed transactions. Note that the transaction manager, for example JmsTransactionManager, still needs to work with the underlying ConnectionFactory, not with this proxy.
Make sure that TransactionAwareConnectionFactoryProxy is the outermost ConnectionFactory of a chain of ConnectionFactory proxies/adapters. TransactionAwareConnectionFactoryProxy can delegate either directly to the target factory or to some intermediary adapter like UserCredentialsConnectionFactoryAdapter.
Delegates to ConnectionFactoryUtils for automatically participating in thread-bound transactions, for example managed by JmsTransactionManager.
createSession
calls and
close
calls on returned Sessions will behave properly within a transaction, that is, always work on the transactional Session. If not within a transaction, normal ConnectionFactory behavior applies.
Note that transactional JMS Sessions will be registered on a per-Connection basis. To share the same JMS Session across a transaction, make sure that you operate on the same JMS Connection handle - either through reusing the handle or through configuring a SingleConnectionFactory underneath.
Returned transactional Session proxies will implement the SessionProxy interface to allow for access to the underlying target Session. This is only intended for accessing vendor-specific Session API or for testing purposes (e.g. to perform manual transaction control). For typical application purposes, simply use the standard JMS Session interface.
org.springframework.jca.cci.connection.TransactionAwareConnectionFactoryProxyProxy for a target CCI javax.resource.cci.ConnectionFactory, adding awareness of Spring-managed transactions. Similar to a transactional JNDI ConnectionFactory as provided by a Java EE server.
Data access code that should remain unaware of Spring's data access support can work with this proxy to seamlessly participate in Spring-managed transactions. Note that the transaction manager, for example the CciLocalTransactionManager, still needs to work with underlying ConnectionFactory, not with this proxy.
Make sure that TransactionAwareConnectionFactoryProxy is the outermost ConnectionFactory of a chain of ConnectionFactory proxies/adapters. TransactionAwareConnectionFactoryProxy can delegate either directly to the target connection pool or to some intermediate proxy/adapter like ConnectionSpecConnectionFactoryAdapter.
Delegates to ConnectionFactoryUtils for automatically participating in thread-bound transactions, for example managed by CciLocalTransactionManager.
getConnection
calls and
close
calls on returned Connections will behave properly within a transaction, i.e. always operate on the transactional Connection. If not within a transaction, normal ConnectionFactory behavior applies.
This proxy allows data access code to work with the plain JCA CCI API and still participate in Spring-managed transactions, similar to CCI code in a Java EE/JTA environment. However, if possible, use Spring's ConnectionFactoryUtils, CciTemplate or CCI operation objects to get transaction participation even without a proxy for the target ConnectionFactory, avoiding the need to define such a proxy in the first place.
NOTE: This ConnectionFactory proxy needs to return wrapped Connections in order to handle close calls properly. Therefore, the returned Connections cannot be cast to a native CCI Connection type or to a connection pool implementation type.
org.springframework.jdbc.datasource.TransactionAwareDataSourceProxyProxy for a target JDBC javax.sql.DataSource, adding awareness of Spring-managed transactions. Similar to a transactional JNDI DataSource as provided by a Java EE server.
Data access code that should remain unaware of Spring's data access support can work with this proxy to seamlessly participate in Spring-managed transactions. Note that the transaction manager, for example DataSourceTransactionManager, still needs to work with the underlying DataSource, not with this proxy.
Make sure that TransactionAwareDataSourceProxy is the outermost DataSource of a chain of DataSource proxies/adapters. TransactionAwareDataSourceProxy can delegate either directly to the target connection pool or to some intermediary proxy/adapter like LazyConnectionDataSourceProxy or UserCredentialsDataSourceAdapter.
Delegates to DataSourceUtils for automatically participating in thread-bound transactions, for example managed by DataSourceTransactionManager.
getConnection
calls and
close
calls on returned Connections will behave properly within a transaction, i.e. always operate on the transactional Connection. If not within a transaction, normal DataSource behavior applies.
This proxy allows data access code to work with the plain JDBC API and still participate in Spring-managed transactions, similar to JDBC code in a Java EE/JTA environment. However, if possible, use Spring's DataSourceUtils, JdbcTemplate or JDBC operation objects to get transaction participation even without a proxy for the target DataSource, avoiding the need to define such a proxy in the first place.
As a further effect, using a transaction-aware DataSource will apply remaining transaction timeouts to all created JDBC (Prepared/Callable)Statement. This means that all operations performed through standard JDBC will automatically participate in Spring-managed transaction timeouts.
NOTE:
This DataSource proxy needs to return wrapped Connections (which implement the ConnectionProxy interface) in order to handle close calls properly. Use
Connection#unwrap
to retrieve the native JDBC Connection.
Template class that simplifies programmatic transaction demarcation and transaction exception handling.
The central method is
#execute
, supporting transactional code that implements the TransactionCallback interface. This template handles the transaction lifecycle and possible exceptions such that neither the TransactionCallback implementation nor the calling code needs to explicitly handle transactions.
Typical usage: Allows for writing low-level data access objects that use resources such as JDBC DataSources but are not transaction-aware themselves. Instead, they can implicitly participate in transactions handled by higher-level application services utilizing this class, making calls to the low-level services via an inner-class callback object.
Can be used within a service implementation via direct instantiation with a transaction manager reference, or get prepared in an application context and passed to services as bean reference. Note: The transaction manager should always be configured as bean in the application context: in the first case given to the service directly, in the second case given to the prepared template.
Supports setting the propagation behavior and the isolation level by name, for convenient configuration in context definitions.
org.springframework.transaction.TransactionTimedOutExceptionException to be thrown when a transaction has timed out.
Thrown by Spring's local transaction strategies if the deadline for a transaction has been reached when an operation is attempted, according to the timeout specified for the given transaction.
Beyond such checks before each transactional operation, Spring's local transaction strategies will also pass appropriate timeout values to resource operations (for example to JDBC Statements, letting the JDBC driver respect the timeout). Such operations will usually throw native resource exceptions (for example, JDBC SQLExceptions) if their operation timeout has been exceeded, to be converted to Spring's DataAccessException in the respective DAO (which might use Spring's JdbcTemplate, for example).
In a JTA environment, it is up to the JTA transaction coordinator to apply transaction timeouts. Usually, the corresponding JTA-aware connection pool will perform timeout checks and throw corresponding native resource exceptions (for example, JDBC SQLExceptions).
org.springframework.transaction.event.TransactionalEventListenerAn EventListener that is invoked according to a TransactionPhase.
If the event is not published within the boundaries of a managed transaction, the event is discarded unless the
#fallbackExecution
flag is explicitly set. If a transaction is running, the event is processed according to its
TransactionPhase
.
Adding org.springframework.core.annotation.Order to your annotated method allows you to prioritize that listener amongst other listeners running before or after transaction completion.
org.springframework.transaction.interceptor.TransactionalProxyA marker interface for manually created transactional proxies.
TransactionAttributeSourcePointcut will ignore such existing transactional proxies during AOP auto-proxying and therefore avoid re-processing transaction metadata on them.
org.springframework.web.servlet.tags.TransformTag
The
<transform>
tag provides transformation for reference data values from controllers and other objects inside a
spring:bind
tag (or a data-bound form element tag from Spring's form tag library).
The BindTag has a PropertyEditor that it uses to transform properties of a bean to a String, usable in HTML forms. This tag uses that PropertyEditor to transform objects passed into this tag.
Attribute Summary Attribute Required? Runtime Expression? Description htmlEscape false true Set HTML escaping for this tag, as boolean value. Overrides the default HTML escaping setting for the current page. scope false true The scope to use when exported the result to a variable. This attribute is only used when var is also set. Possible values are page, request, session and application. value true true The value to transform. This is the actual object you want to have transformed (for instance a Date). Using the PropertyEditor that is currently in use by the 'spring:bind' tag. var false true The string to use when binding the result to the page, request, session or application scope. If not specified, the result gets outputted to the writer (i.e. typically directly to the JSP). org.springframework.transaction.config.TxNamespaceHandler
NamespaceHandler
allowing for the configuration of declarative transaction management using either XML or using annotations.
This namespace handler is the central piece of functionality in the Spring transaction management facilities and offers two approaches to declaratively manage transactions.
One approach uses transaction semantics defined in XML using the
<tx:advice>
elements, the other uses annotations in combination with the
<tx:annotation-driven>
element. Both approached are detailed to great extent in the Spring reference manual.
A reference to a type appearing in a class, field or method declaration, or on an instruction. Such a reference designates the part of the class where the referenced type is appearing (e.g. an 'extends', 'implements' or 'throws' clause, a 'new' instruction, a 'catch' clause, a type cast, a local variable declaration, etc).
org.springframework.beans.factory.config.TypedStringValueHolder for a typed String value. Can be added to bean definitions in order to explicitly specify a target type for a String value, for example for collection elements.
This holder will just store the String value and the target type. The actual conversion will be performed by the bean factory.
org.springframework.beans.propertyeditors.URIEditor
Editor for
java.net.URI
, to directly populate a URI property instead of using a String property as bridge.
Supports Spring-style URI notation: any fully qualified standard URI ("file:", "http:", etc) and Spring's special "classpath:" pseudo-URL, which will be resolved to a corresponding URI.
By default, this editor will encode Strings into URIs. For instance, a space will be encoded into
%20
. This behavior can be changed by calling the
#URIEditor(boolean)
constructor.
Note: A URI is more relaxed than a URL in that it does not require a valid protocol to be specified. Any scheme within a valid URI syntax is allowed, even without a matching protocol handler being registered.
org.springframework.beans.propertyeditors.URLEditor
Editor for
java.net.URL
, to directly populate a URL property instead of using a String property as bridge.
Supports Spring-style URL notation: any fully qualified standard URL ("file:", "http:", etc) and Spring's special "classpath:" pseudo-URL, as well as Spring's context-specific relative file paths.
Note: A URL must specify a valid protocol, else it will be rejected upfront. However, the target resource does not necessarily have to exist at the time of URL creation; this depends on the specific resource type.
org.springframework.jmx.export.notification.UnableToSendNotificationExceptionThrown when a JMX javax.management.Notification is unable to be sent.
The root cause of just why a particular notification could not be sent will
typically
be available via the
#getCause()
property.
A WebSocket
RequestUpgradeStrategy
for WildFly and its underlying Undertow web server. Also compatible with embedded Undertow usage.
Requires Undertow 1.3.5+ as of Spring Framework 5.0.
org.springframework.web.socket.sockjs.client.UndertowXhrTransportAn XHR transport based on Undertow's io.undertow.client.UndertowClient. Requires Undertow 1.3 or 1.4, including XNIO, as of Spring Framework 5.0.
When used for testing purposes (e.g. load testing) or for specific use cases (like HTTPS configuration), a custom OptionMap should be provided:
OptionMap optionMap = OptionMap.builder() .set(Options.WORKER_IO_THREADS, 8) .set(Options.TCP_NODELAY, true) .set(Options.KEEP_ALIVE, true) .set(Options.WORKER_NAME, "SockJSClient") .getMap(); UndertowXhrTransport transport = new UndertowXhrTransport(optionMap);
org.springframework.jdbc.object.UpdatableSqlQuery
Reusable RDBMS query in which concrete subclasses must implement the abstract updateRow(ResultSet, int, context) method to update each row of the JDBC ResultSet and optionally map contents into an object.
Subclasses can be constructed providing SQL, parameter types and a DataSource. SQL will often vary between subclasses.
org.springframework.web.servlet.mvc.method.annotation.UriComponentsBuilderMethodArgumentResolverResolvers argument values of type UriComponentsBuilder.
The returned instance is initialized via
ServletUriComponentsBuilder#fromServletMapping(HttpServletRequest)
.
Represents a URI template. A URI template is a URI-like String that contains variables enclosed by braces (
{}
) which can be expanded to produce an actual URI.
See
#expand(Map)
,
#expand(Object[])
, and
#match(String)
for example usages.
This class is designed to be thread-safe and reusable, allowing for any number of expand or match calls.
org.springframework.web.util.UriUtilsUtility class for URI encoding and decoding based on RFC 3986. Offers encoding methods for the various URI components.
All
encode*(String, String)
methods in this class operate in a similar way:
%
xy
" format.
Provide a per request CorsConfiguration instance based on a collection of CorsConfiguration mapped on path patterns.
Exact path mapping URIs (such as
"/admin"
) are supported as well as Ant-style path patterns (such as
"/admin/**"
).
Provide a per reactive request CorsConfiguration instance based on a collection of CorsConfiguration mapped on path patterns.
Exact path mapping URIs (such as
"/admin"
) are supported as well as Ant-style path patterns (such as
"/admin/**"
).
Simple
Controller
implementation that transforms the virtual path of a URL into a view name and returns that view.
Can optionally prepend a
prefix
and/or append a
suffix
to build the viewname from the URL filename.
Find some examples below:
"/index" -> "index"
"/index.html" -> "index"
"/index.html"
+ prefix
"pre_"
and suffix
"_suf" -> "pre_index_suf"
"/products/view.html" -> "products/view"
Thanks to David Barri for suggesting prefix/suffix support!
org.springframework.test.web.servlet.htmlunit.UrlRegexRequestMatcher
A WebRequestMatcher that allows matching on
WebRequest#getUrl().toExternalForm()
using a regular expression.
For example, if you would like to match on the domain
code.jquery.com
, you might want to use the following.
WebRequestMatcher cdnMatcher = new UrlRegexRequestMatcher(".*?//code.jquery.com/.*");
org.springframework.web.servlet.tags.UrlTag
The
<url>
tag creates URLs. Modeled after the JSTL c:url tag with backwards compatibility in mind.
Enhancements to the JSTL functionality include:
Template URI variables are indicated in the
'value'
attribute and marked by braces '{variableName}'. The braces and attribute name are replaced by the URL encoded value of a parameter defined with the spring:param tag in the body of the url tag. If no parameter is available the literal value is passed through. Params matched to template variables will not be added to the query string.
Use of the spring:param tag for URI template variables is strongly recommended over direct EL substitution as the values are URL encoded. Failure to properly encode URL can leave an application vulnerable to XSS and other injection attacks.
URLs can be HTML/XML escaped by setting the
'htmlEscape'
attribute to 'true'. Detects an HTML escaping setting, either on this tag instance, the page level, or the
web.xml
level. The default is 'false'. When setting the URL value into a variable, escaping is not recommended.
Example usage:
<spring:url value="/url/path/{variableName}"> <spring:param name="variableName" value="more than JSTL c:url" /> </spring:url>
The above results in:
/currentApplicationContext/url/path/more%20than%20JSTL%20c%3Aurl
An adapter for a target JMS javax.jms.ConnectionFactory, applying the given user credentials to every standard
createConnection()
call, that is, implicitly invoking
createConnection(username, password)
on the target. All other methods simply delegate to the corresponding methods of the target ConnectionFactory.
Can be used to proxy a target JNDI ConnectionFactory that does not have user credentials configured. Client code can work with the ConnectionFactory without passing in username and password on every
createConnection()
call.
In the following example, client code can simply transparently work with the preconfigured "myConnectionFactory", implicitly accessing "myTargetConnectionFactory" with the specified user credentials.
<bean id="myTargetConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jms/mycf"/> </bean> <bean id="myConnectionFactory" class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter"> <property name="targetConnectionFactory" ref="myTargetConnectionFactory"/> <property name="username" value="myusername"/> <property name="password" value="mypassword"/> </bean>
If the "username" is empty, this proxy will simply delegate to the standard
createConnection()
method of the target ConnectionFactory. This can be used to keep a UserCredentialsConnectionFactoryAdapter bean definition just for the
option
of implicitly passing in user credentials if the particular target ConnectionFactory requires it.
Adapter for a JTA UserTransaction handle, taking a JTA javax.transaction.TransactionManager reference and creating a JTA javax.transaction.UserTransaction handle for it.
The JTA UserTransaction interface is an exact subset of the JTA TransactionManager interface. Unfortunately, it does not serve as super-interface of TransactionManager, though, which requires an adapter such as this class to be used when intending to talk to a TransactionManager handle through the UserTransaction interface.
Used internally by Spring's JtaTransactionManager for certain scenarios. Not intended for direct use in application code.
org.springframework.validation.annotation.ValidatedVariant of JSR-303's javax.validation.Valid, supporting the specification of validation groups. Designed for convenient use with Spring's JSR-303 support but not JSR-303 specific.
Can be used e.g. with Spring MVC handler methods arguments. Supported through org.springframework.validation.SmartValidator's validation hint concept, with validation group classes acting as hint objects.
Can also be used with method level validation, indicating that a specific class is supposed to be validated at the method level (acting as a pointcut for the corresponding validation interceptor), but also optionally specifying the validation groups for method-level validation in the annotated class. Applying this annotation at the method level allows for overriding the validation groups for a specific method but does not serve as a pointcut; a class-level annotation is nevertheless necessary to trigger method validation for a specific bean to begin with. Can also be used as a meta-annotation on a custom stereotype annotation or a custom group-specific validated annotation.
org.springframework.validation.ValidationUtilsUtility class offering convenient methods for invoking a Validator and for rejecting empty fields.
Checks for an empty field in
Validator
implementations can become one-liners when using
#rejectIfEmpty
or
#rejectIfEmptyOrWhitespace
.
Annotation at the field or method/constructor parameter level that indicates a default value expression for the affected argument.
Typically used for expression-driven dependency injection. Also supported for dynamic resolution of handler method parameters, e.g. in Spring MVC.
A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions.
Note that actual processing of the
@Value
annotation is performed by a org.springframework.beans.factory.config.BeanPostProcessor which in turn means that you
cannot
use
@Value
within org.springframework.beans.factory.config.BeanPostProcessor or org.springframework.beans.factory.config.BeanFactoryPostProcessor types. Please consult the javadoc for the AutowiredAnnotationBeanPostProcessor class (which, by default, checks for the presence of this annotation).
Resolves request paths containing a version string that can be used as part of an HTTP caching strategy in which a resource is cached with a date in the distant future (e.g. 1 year) and cached until the version, and therefore the URL, is changed.
Different versioning strategies exist, and this resolver must be configured with one or more such strategies along with path mappings to indicate which strategy applies to which resources.
ContentVersionStrategy
is a good default choice except in cases where it cannot be used. Most notably the
ContentVersionStrategy
cannot be combined with JavaScript module loaders. For such cases the
FixedVersionStrategy
is a better choice.
Note that using this resolver to serve CSS files means that the CssLinkResourceTransformer should also be used in order to modify links within CSS files to also contain the appropriate versions generated by this resolver.
org.springframework.web.servlet.resource.VersionResourceResolverResolves request paths containing a version string that can be used as part of an HTTP caching strategy in which a resource is cached with a date in the distant future (e.g. 1 year) and cached until the version, and therefore the URL, is changed.
Different versioning strategies exist, and this resolver must be configured with one or more such strategies along with path mappings to indicate which strategy applies to which resources.
ContentVersionStrategy
is a good default choice except in cases where it cannot be used. Most notably the
ContentVersionStrategy
cannot be combined with JavaScript module loaders. For such cases the
FixedVersionStrategy
is a better choice.
Note that using this resolver to serve CSS files means that the CssLinkResourceTransformer should also be used in order to modify links within CSS files to also contain the appropriate versions generated by this resolver.
org.springframework.core.io.VfsUtilsUtility for detecting and accessing JBoss VFS in the classpath.
As of Spring 4.0, this class supports VFS 3.x on JBoss AS 6+ (package
org.jboss.vfs
) and is in particular compatible with JBoss AS 7 and WildFly 8.
Thanks go to Marius Bogoevici for the initial patch. Note: This is an internal class and should not be used outside the framework.
org.springframework.web.servlet.mvc.method.annotation.ViewMethodReturnValueHandlerHandles return values that are of type View.
A
null
return value is left as-is leaving it to the configured RequestToViewNameTranslator to select a view name by convention.
A View return type has a set purpose. Therefore this handler should be configured ahead of handlers that support any return value type annotated with
@ModelAttribute
or
@ResponseBody
to ensure they don't take over.
Handles return values of types
void
and
String
interpreting them as view name reference. As of 4.2, it also handles general
CharSequence
types, e.g.
StringBuilder
or Groovy's
GString
, as view names.
A
null
return value, either due to a
void
return type or as the actual return value is left as-is allowing the configured RequestToViewNameTranslator to select a view name by convention.
A String return value can be interpreted in more than one ways depending on the presence of annotations like
@ModelAttribute
or
@ResponseBody
. Therefore this handler should be configured after the handlers that support these annotations.
Parse the
view-resolvers
MVC namespace element and register org.springframework.web.servlet.ViewResolver bean definitions.
All registered resolvers are wrapped in a single (composite) ViewResolver with its order property set to 0 so that other external resolvers may be ordered before or after it.
When content negotiation is enabled the order property is set to highest priority instead with the ContentNegotiatingViewResolver encapsulating all other registered view resolver instances. That way the resolvers registered through the MVC namespace form self-encapsulated resolver chain.
org.springframework.test.web.servlet.result.ViewResultMatchersFactory for assertions on the selected view.
An instance of this class is typically accessed via
MockMvcResultMatchers#view
.
ClassFileTransformer-based weaver, allowing for a list of transformers to be applied on a class byte array. Normally used inside class loaders.
Note: This class is deliberately implemented for minimal external dependencies, since it is included in weaver jars (to be deployed into application servers).
org.springframework.test.context.web.WebAppConfiguration
@WebAppConfiguration
is a class-level annotation that is used to declare that the
ApplicationContext
loaded for an integration test should be a org.springframework.web.context.WebApplicationContext.
The presence of
@WebAppConfiguration
on a test class indicates that a
WebApplicationContext
should be loaded for the test using a default for the path to the root of the web application. To override the default, specify an explicit resource path via the
#value
attribute.
Note that
@WebAppConfiguration
must be used in conjunction with org.springframework.test.context.ContextConfiguration, either within a single test class or within a test class hierarchy.
As of Spring Framework 4.0, this annotation may be used as a meta-annotation to create custom composed annotations .
org.springframework.web.util.WebAppRootListenerListener that sets a system property to the web application root directory. The key of the system property can be defined with the "webAppRootKey" init parameter at the servlet context level (i.e. context-param in web.xml), the default key is "webapp.root".
Can be used for toolkits that support substitution with system properties (i.e. System.getProperty values), like log4j's "${key}" syntax within log file locations.
Note: This listener should be placed before ContextLoaderListener in
web.xml
, at least when used for log4j. Log4jConfigListener sets the system property implicitly, so there's no need for this listener in addition to it.
WARNING : Some containers, e.g. Tomcat, do NOT keep system properties separate per web app. You have to use unique "webAppRootKey" context-params per web app then, to avoid clashes. Other containers like Resin do isolate each web app's system properties: Here you can use the default key (i.e. no "webAppRootKey" context-param at all) without worrying.
WARNING : The WAR file containing the web application needs to be expanded to allow for setting the web app root system property. This is by default not the case when a WAR file gets deployed to WebLogic, for example. Do not use this listener in such an environment!
org.springframework.web.jsf.el.WebApplicationContextFacesELResolver
Special JSF
ELResolver
that exposes the Spring
WebApplicationContext
instance under a variable named "webApplicationContext".
In contrast to SpringBeanFacesELResolver, this ELResolver variant does not resolve JSF variable names as Spring bean names. It rather exposes Spring's root WebApplicationContext itself under a special name, and is able to resolve "webApplicationContext.mySpringManagedBusinessObject" dereferences to Spring-defined beans in that application context.
Configure this resolver in your
faces-config.xml
file as follows:
<application> ... <el-resolver>org.springframework.web.jsf.el.WebApplicationContextFacesELResolver</el-resolver> </application>
org.springframework.web.context.support.WebApplicationContextUtils
Convenience methods for retrieving the root WebApplicationContext for a given ServletContext. This is useful for programmatically accessing a Spring application context from within custom web views or MVC actions.
Note that there are more convenient ways of accessing the root context for many web frameworks, either part of Spring or available as an external library. This helper class is just the most generic way to access the root context.
org.springframework.web.WebApplicationInitializer
Interface to be implemented in Servlet 3.0+ environments in order to configure the ServletContext programmatically -- as opposed to (or possibly in conjunction with) the traditional
web.xml
-based approach.
Implementations of this SPI will be detected automatically by , which itself is bootstrapped automatically by any Servlet 3.0 container. See SpringServletContainerInitializer for details on this bootstrapping mechanism.
Example The traditional, XML-based approach Most Spring users building a web application will need to register Spring's
DispatcherServlet
. For reference, in WEB-INF/web.xml, this would typically be done as follows:
<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
The code-based approach with
WebApplicationInitializer
Here is the equivalent
DispatcherServlet
registration logic,
WebApplicationInitializer
-style:
public class MyWebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { XmlWebApplicationContext appContext = new XmlWebApplicationContext(); appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml"); ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(appContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
As an alternative to the above, you can also extend from . As you can see, thanks to Servlet 3.0's new
ServletContext#addServlet
method we're actually registering an
instance
of the
DispatcherServlet
, and this means that the
DispatcherServlet
can now be treated like any other object -- receiving constructor injection of its application context in this case.
This style is both simpler and more concise. There is no concern for dealing with init-params, etc, just normal JavaBean-style properties and constructor arguments. You are free to create and work with your Spring application contexts as necessary before injecting them into the
DispatcherServlet
.
Most major Spring Web components have been updated to support this style of registration. You'll find that
DispatcherServlet
,
FrameworkServlet
,
ContextLoaderListener
and
DelegatingFilterProxy
all now support constructor arguments. Even if a component (e.g. non-Spring, other third party) has not been specifically updated for use within
WebApplicationInitializers
, they still may be used in any case. The Servlet 3.0
ServletContext
API allows for setting init-params, context-params, etc programmatically.
WEB-INF/web.xml
was successfully replaced with code in the form of a
WebApplicationInitializer
, but the actual
dispatcher-config.xml
Spring configuration remained XML-based.
WebApplicationInitializer
is a perfect fit for use with Spring's code-based
@Configuration
classes. See @ Javadoc for complete details, but the following example demonstrates refactoring to use Spring's org.springframework.web.context.support.AnnotationConfigWebApplicationContext in lieu of
XmlWebApplicationContext
, and user-defined
@Configuration
classes
AppConfig
and
DispatcherConfig
instead of Spring XML files. This example also goes a bit beyond those above to demonstrate typical configuration of the 'root' application context and registration of the
ContextLoaderListener
:
public class MyWebAppInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext container) { // Create the 'root' Spring application context AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(AppConfig.class); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(rootContext)); // Create the dispatcher servlet's Spring application context AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(DispatcherConfig.class); // Register and map the dispatcher servlet ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }
As an alternative to the above, you can also extend from . Remember that
WebApplicationInitializer
implementations are
detected automatically
-- so you are free to package them within your application as you see fit. Ordering
WebApplicationInitializer
execution
WebApplicationInitializer
implementations may optionally be annotated at the class level with Spring's @org.springframework.core.annotation.Order annotation or may implement Spring's org.springframework.core.Ordered interface. If so, the initializers will be ordered prior to invocation. This provides a mechanism for users to ensure the order in which servlet container initialization occurs. Use of this feature is expected to be rare, as typical applications will likely centralize all container initialization within a single
WebApplicationInitializer
. Caveats web.xml versioning
WEB-INF/web.xml
and
WebApplicationInitializer
use are not mutually exclusive; for example, web.xml can register one servlet, and a
WebApplicationInitializer
can register another. An initializer can even
modify
registrations performed in
web.xml
through methods such as
ServletContext#getServletRegistration(String)
.
However, if
WEB-INF/web.xml
is present in the application, its
version
attribute must be set to "3.0" or greater, otherwise
ServletContainerInitializer
bootstrapping will be ignored by the servlet container.
Apache Tomcat maps its internal
DefaultServlet
to "/", and on Tomcat versions <= 7.0.14, this servlet mapping
cannot be overridden programmatically
. 7.0.15 fixes this issue. Overriding the "/" servlet mapping has also been tested successfully under GlassFish 3.1.
SPI for resolving custom arguments for a specific handler method parameter. Typically implemented to detect special parameter types, resolving well-known argument values for them.
A typical implementation could look like as follows:
public class MySpecialArgumentResolver implements WebArgumentResolver { public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) { if (methodParameter.getParameterType().equals(MySpecialArg.class)) { return new MySpecialArg("myValue"); } return UNRESOLVED; } }
org.springframework.test.web.servlet.htmlunit.webdriver.WebConnectionHtmlUnitDriver
WebConnectionHtmlUnitDriver
enables configuration of the WebConnection for an HtmlUnitDriver instance.
This is useful because it allows a org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection to be injected.
org.springframework.web.servlet.mvc.WebContentInterceptorHandler interceptor that checks the request and prepares the response. Checks for supported methods and a required session, and applies the specified org.springframework.http.CacheControl builder. See superclass bean properties for configuration options.
All the settings supported by this interceptor can also be set on AbstractController. This interceptor is mainly intended for applying checks and preparations to a set of controllers mapped by a HandlerMapping.
org.springframework.web.reactive.config.WebFluxConfigurationSupportThe main class for Spring WebFlux configuration.
Import directly or extend and override protected methods to customize.
org.springframework.web.reactive.resource.WebJarsResourceResolver
A
ResourceResolver
that delegates to the chain to locate a resource and then attempts to find a matching versioned resource contained in a WebJar JAR file.
This allows WebJars.org users to write version agnostic paths in their templates, like
<script src="/jquery/jquery.min.js"/>
. This path will be resolved to the unique version
<script src="/jquery/1.2.0/jquery.min.js"/>
, which is a better fit for HTTP caching and version management in applications.
This also resolves resources for version agnostic HTTP requests
"GET /jquery/jquery.min.js"
.
This resolver requires the "org.webjars:webjars-locator" library on classpath, and is automatically registered if that library is present.
org.springframework.web.servlet.resource.WebJarsResourceResolver
A
ResourceResolver
that delegates to the chain to locate a resource and then attempts to find a matching versioned resource contained in a WebJar JAR file.
This allows WebJars.org users to write version agnostic paths in their templates, like
<script src="/jquery/jquery.min.js"/>
. This path will be resolved to the unique version
<script src="/jquery/1.2.0/jquery.min.js"/>
, which is a better fit for HTTP caching and version management in applications.
This also resolves resources for version agnostic HTTP requests
"GET /jquery/jquery.min.js"
.
This resolver requires the "org.webjars:webjars-locator" library on classpath, and is automatically registered if that library is present.
org.springframework.transaction.jta.WebLogicJtaTransactionManagerSpecial JtaTransactionManager variant for BEA WebLogic (9.0 and higher). Supports the full power of Spring's transaction definitions on WebLogic's transaction coordinator, beyond standard JTA : transaction names, per-transaction isolation levels, and proper resuming of transactions in all cases.
Uses WebLogic's special
begin(name)
method to start a JTA transaction, in order to make
Spring-driven transactions visible in WebLogic's transaction monitor
. In case of Spring's declarative transactions, the exposed name will (by default) be the fully-qualified class name + "." + method name.
Supports a per-transaction isolation level through WebLogic's corresponding JTA transaction property "ISOLATION LEVEL". This will apply the specified isolation level (e.g. ISOLATION_SERIALIZABLE) to all JDBC Connections that participate in the given transaction.
Invokes WebLogic's special
forceResume
method if standard JTA resume failed, to
also resume if the target transaction was marked rollback-only
. If you're not relying on this feature of transaction suspension in the first place, Spring's standard JtaTransactionManager will behave properly too.
By default, the JTA UserTransaction and TransactionManager handles are fetched directly from WebLogic's
TransactionHelper
. This can be overridden by specifying "userTransaction"/"userTransactionName" and "transactionManager"/"transactionManagerName", passing in existing handles or specifying corresponding JNDI locations to look up.
NOTE: This JtaTransactionManager is intended to refine specific transaction demarcation behavior on Spring's side. It will happily co-exist with independently configured WebLogic transaction strategies in your persistence provider, with no need to specifically connect those setups in any way.
org.springframework.instrument.classloading.weblogic.WebLogicLoadTimeWeaverLoadTimeWeaver implementation for WebLogic's instrumentable ClassLoader.
NOTE: Requires BEA WebLogic version 10 or higher.
org.springframework.test.context.web.WebMergedContextConfiguration
WebMergedContextConfiguration
encapsulates the
merged
context configuration declared on a test class and all of its superclasses via org.springframework.test.context.ContextConfiguration, WebAppConfiguration, and org.springframework.test.context.ActiveProfiles.
WebMergedContextConfiguration
extends the contract of MergedContextConfiguration by adding support for the
configured via
@WebAppConfiguration
. This allows the org.springframework.test.context.TestContext to properly cache the corresponding that was loaded using properties of this
WebMergedContextConfiguration
.
This is the main class providing the configuration behind the MVC Java config. It is typically imported by adding EnableWebMvc to an application Configuration class. An alternative more advanced option is to extend directly from this class and override methods as necessary, remembering to add Configuration to the subclass and Bean to overridden Bean methods. For more details see the javadoc of EnableWebMvc.
This class registers the following HandlerMappings:
Integer.MAX_VALUE-1
to serve static resource requests.
Integer.MAX_VALUE
to forward requests to the default servlet.
Registers these HandlerAdapters:
Registers a HandlerExceptionResolverComposite with this chain of exception resolvers:
Registers an AntPathMatcher and a UrlPathHelper to be used by:
Both the RequestMappingHandlerAdapter and the ExceptionHandlerExceptionResolver are configured with default instances of the following by default:
Special org.springframework.validation.DataBinder to perform data binding from web request parameters to JavaBeans, including support for multipart files.
See the DataBinder/WebDataBinder superclasses for customization options, which include specifying allowed/required fields, and registering custom property editors.
Can also used for manual data binding in custom web controllers or interceptors that build on Spring's org.springframework.web.context.request.WebRequest abstraction: e.g. in a org.springframework.web.context.request.WebRequestInterceptor implementation. Simply instantiate a WebRequestDataBinder for each binding process, and invoke
bind
with the current WebRequest as argument:
MyBean myBean = new MyBean(); // apply binder to custom target object WebRequestDataBinder binder = new WebRequestDataBinder(myBean); // register custom editors, if desired binder.registerCustomEditor(...); // trigger actual binding of request parameters binder.bind(request); // optionally evaluate binding errors Errors errors = binder.getErrors(); ...
org.springframework.web.socket.WebSocketExtension
Represents a WebSocket extension as defined in the RFC 6455. WebSocket extensions add protocol features to the WebSocket protocol. The extensions used within a session are negotiated during the handshake phase as follows:
WebSocket Extension HTTP headers may include parameters and follow RFC 7230 section 3.2
Note that the order of extensions in HTTP headers defines their order of execution, e.g. extensions "foo, bar" will be executed as "bar(foo(message))".
org.springframework.web.socket.handler.WebSocketHandlerDecoratorWraps another org.springframework.web.socket.WebSocketHandler instance and delegates to it.
Also provides a
#getDelegate()
method to return the decorated handler as well as a
#getLastHandler()
method to go through all nested delegates and return the "last" handler.
A factory for applying decorators to a WebSocketHandler.
Decoration should be done through sub-classing org.springframework.web.socket.handler.WebSocketHandlerDecorator to allow any code to traverse decorators and/or unwrap the original handler when necessary .
org.springframework.web.socket.server.support.WebSocketHttpRequestHandlerA HttpRequestHandler for processing WebSocket handshake requests.
This is the main class to use when configuring a server WebSocket at a specific URL. It is a very thin wrapper around a WebSocketHandler and a HandshakeHandler, also adapting the HttpServletRequest and HttpServletResponse to ServerHttpRequest and ServerHttpResponse, respectively.
org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupportExtends AbstractMessageBrokerConfiguration and adds configuration for receiving and responding to STOMP messages from WebSocket clients.
Typically used in conjunction with EnableWebSocketMessageBroker but can also be extended directly.
org.springframework.web.socket.sockjs.transport.handler.WebSocketTransportHandlerWebSocket-based TransportHandler. Uses SockJsWebSocketHandler and WebSocketServerSockJsSession to add SockJS processing.
Also implements HandshakeHandler to support raw WebSocket communication at SockJS URL "/websocket".
org.springframework.jdbc.datasource.WebSphereDataSourceAdapterDataSource implementation that delegates all calls to a WebSphere target DataSource, typically obtained from JNDI, applying a current isolation level and/or current user credentials to every Connection obtained from it.
Uses IBM-specific API to get a JDBC Connection with a specific isolation level (and read-only flag) from a WebSphere DataSource (
IBM code example
). Supports the transaction-specific isolation level exposed by
org.springframework.transaction.support.TransactionSynchronizationManager#getCurrentTransactionIsolationLevel()
. It's also possible to specify a default isolation level, to be applied when the current Spring-managed transaction does not define a specific isolation level.
Usage example, defining the target DataSource as an inner-bean JNDI lookup (of course, you can link to any WebSphere DataSource through a bean reference):
<bean id="myDataSource" class="org.springframework.jdbc.datasource.WebSphereDataSourceAdapter"> <property name="targetDataSource"> <bean class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="jdbc/myds"/> </bean> </property> </bean>
Thanks to Ricardo Olivieri for submitting the original implementation of this approach!
org.springframework.web.socket.server.standard.WebSphereRequestUpgradeStrategy
WebSphere support for upgrading an HttpServletRequest during a WebSocket handshake. To modify properties of the underlying javax.websocket.server.ServerContainer you can use ServletServerContainerFactoryBean in XML configuration or, when using Java configuration, access the container instance through the "javax.websocket.server.ServerContainer" ServletContext attribute.
Tested with WAS Liberty beta (August 2015) for the upcoming 8.5.5.7 release.
org.springframework.transaction.jta.WebSphereUowTransactionManagerWebSphere-specific PlatformTransactionManager implementation that delegates to a com.ibm.wsspi.uow.UOWManager instance, obtained from WebSphere's JNDI environment. This allows Spring to leverage the full power of the WebSphere transaction coordinator, including transaction suspension, in a manner that is perfectly compliant with officially supported WebSphere API.
The CallbackPreferringPlatformTransactionManager interface implemented by this class indicates that callers should preferably pass in a TransactionCallback through the
#execute
method, which will be handled through the callback-based WebSphere UOWManager API instead of through standard JTA API (UserTransaction / TransactionManager). This avoids the use of the non-public
javax.transaction.TransactionManager
API on WebSphere, staying within supported WebSphere API boundaries.
This transaction manager implementation derives from Spring's standard JtaTransactionManager, inheriting the capability to support programmatic transaction demarcation via
getTransaction
/
commit
/
rollback
calls through a JTA UserTransaction handle, for callers that do not use the TransactionCallback-based
#execute
method. However, transaction suspension is
not
supported in this
getTransaction
style (unless you explicitly specify a
#setTransactionManager
reference, despite the official WebSphere recommendations). Use the
#execute
style for any code that might require transaction suspension.
This transaction manager is compatible with WebSphere 6.1.0.9 and above. The default JNDI location for the UOWManager is "java:comp/websphere/UOWManager". If the location happens to differ according to your WebSphere documentation, simply specify the actual location through this transaction manager's "uowManagerName" bean property.
NOTE: This JtaTransactionManager is intended to refine specific transaction demarcation behavior on Spring's side. It will happily co-exist with independently configured WebSphere transaction strategies in your persistence provider, with no need to specifically connect those setups in any way.
org.springframework.test.context.web.WebTestContextBootstrapperWeb-specific implementation of the TestContextBootstrapper SPI.
TaskExecutor implementation that delegates to a CommonJ WorkManager, implementing the commonj.work.WorkManager interface, which either needs to be specified as reference or through the JNDI name.
This is the central convenience class for setting up a CommonJ WorkManager in a Spring context.
Also implements the CommonJ WorkManager interface itself, delegating all calls to the target WorkManager. Hence, a caller can choose whether it wants to talk to this executor through the Spring TaskExecutor interface or the CommonJ WorkManager interface.
The CommonJ WorkManager will usually be retrieved from the application server's JNDI environment, as defined in the server's management console.
Note: On the upcoming EE 7 compliant versions of WebLogic and WebSphere, a org.springframework.scheduling.concurrent.DefaultManagedTaskExecutor should be preferred, following JSR-236 support in Java EE 7.
org.springframework.jca.work.WorkManagerTaskExecutororg.springframework.core.task.TaskExecutor implementation that delegates to a JCA 1.7 WorkManager, implementing the javax.resource.spi.work.WorkManager interface.
This is mainly intended for use within a JCA ResourceAdapter implementation, but may also be used in a standalone environment, delegating to a locally embedded WorkManager implementation (such as Geronimo's).
Also implements the JCA 1.7 WorkManager interface itself, delegating all calls to the target WorkManager. Hence, a caller can choose whether it wants to talk to this executor through the Spring TaskExecutor interface or the WorkManager interface.
This adapter is also capable of obtaining a JCA WorkManager from JNDI. This is for example appropriate on the Geronimo application server, where WorkManager GBeans (e.g. Geronimo's default "DefaultWorkManager" GBean) can be linked into the Java EE environment through "gbean-ref" entries in the
geronimo-web.xml
deployment descriptor.
Implementation of the
Marshaller
interface for XStream.
By default, XStream does not require any further configuration and can (un)marshal any class on the classpath. As such, it is
not recommended to use the
XStreamMarshaller
to unmarshal XML from external sources
(i.e. the Web), as this can result in
security vulnerabilities
. If you do use the
XStreamMarshaller
to unmarshal external XML, set the
supportedClasses
and
converters
properties (possibly using a CatchAllConverter) or override the
#customizeXStream(XStream)
method to make sure it only accepts the classes you want it to support.
Due to XStream's API, it is required to set the encoding used for writing to OutputStreams. It defaults to
UTF-8
.
NOTE: XStream is an XML serialization library, not a data binding library. Therefore, it has limited namespace support. As such, it is rather unsuitable for usage within Web Services.
This marshaller requires XStream 1.4.5 or higher, as of Spring 4.3. Note that XStream construction has been reworked in 4.0, with the stream driver and the class loader getting passed into XStream itself now.
org.springframework.beans.factory.xml.XmlBeanFactoryConvenience extension of DefaultListableBeanFactory that reads bean definitions from an XML document. Delegates to XmlBeanDefinitionReader underneath; effectively equivalent to using an XmlBeanDefinitionReader with a DefaultListableBeanFactory.
The structure, element and attribute names of the required XML document are hard-coded in this class. (Of course a transform could be run if necessary to produce this format). "beans" doesn't need to be the root element of the XML document: This class will parse all bean definition elements in the XML file.
This class registers each bean definition with the DefaultListableBeanFactory superclass, and relies on the latter's implementation of the BeanFactory interface. It supports singletons, prototypes, and references to either of these kinds of bean. See
"spring-beans-3.x.xsd"
(or historically,
"spring-beans-2.0.dtd"
) for details on options and configuration style.
For advanced needs, consider using a DefaultListableBeanFactory with an XmlBeanDefinitionReader. The latter allows for reading from multiple XML resources and is highly configurable in its actual XML parsing behavior.
org.springframework.http.codec.xml.XmlEventDecoderDecodes a DataBuffer stream into a stream of XMLEvents. That is, given the following XML:
<root> <child>foo</child> <child>bar</child> </root>
this method with result in a flux with the following events:
root
child
foo
child
child
bar
child
root
A org.springframework.web.servlet.ViewResolver implementation that uses bean definitions in a dedicated XML file for view definitions, specified by resource location. The file will typically be located in the WEB-INF directory; the default is "/WEB-INF/views.xml".
This
ViewResolver
does not support internationalization at the level of its definition resources. Consider ResourceBundleViewResolver if you need to apply different view resources per locale.
Note: This
ViewResolver
implements the Ordered interface in order to allow for flexible participation in
ViewResolver
chaining. For example, some special views could be defined via this
ViewResolver
(giving it 0 as "order" value), while all remaining views could be resolved by a UrlBasedViewResolver.
org.springframework.web.context.WebApplicationContext implementation which takes its configuration from XML documents, understood by an org.springframework.beans.factory.xml.XmlBeanDefinitionReader. This is essentially the equivalent of org.springframework.context.support.GenericXmlApplicationContext for a web environment.
By default, the configuration will be taken from "/WEB-INF/applicationContext.xml" for the root context, and "/WEB-INF/test-servlet.xml" for a context with the namespace "test-servlet" (like for a DispatcherServlet instance with the servlet-name "test").
The config location defaults can be overridden via the "contextConfigLocation" context-param of org.springframework.web.context.ContextLoader and servlet init-param of org.springframework.web.servlet.FrameworkServlet. Config locations can either denote concrete files like "/WEB-INF/context.xml" or Ant-style patterns like "/WEB-INF/*-context.xml" (see org.springframework.util.PathMatcher javadoc for pattern details).
Note: In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra XML file.
For a WebApplicationContext that reads in a different bean definition format, create an analogous subclass of AbstractRefreshableWebApplicationContext. Such a context implementation can be specified as "contextClass" context-param for ContextLoader or "contextClass" init-param for FrameworkServlet.
org.springframework.test.web.servlet.result.XpathResultMatchersFactory for assertions on the response content using XPath expressions.
An instance of this class is typically accessed via
MockMvcResultMatchers#xpath
.
XSLT-driven View that allows for response context to be rendered as the result of an XSLT transformation.
The XSLT Source object is supplied as a parameter in the model and then
detected
during response rendering. Users can either specify a specific entry in the model via the
sourceKey
property or have Spring locate the Source object. This class also provides basic conversion of objects into Source implementations. See
here
for more details.
All model parameters are passed to the XSLT Transformer as parameters. In addition the user can configure
output properties
to be passed to the Transformer.
Factory for a
Map
that reads from a YAML source, preserving the YAML-declared value types and their structure.
YAML is a nice human-readable format for configuration, and it has some useful hierarchical properties. It's more or less a superset of JSON, so it has a lot of similar features.
If multiple resources are provided the later ones will override entries in the earlier ones hierarchically; that is, all entries with the same nested key of type
Map
at any depth are merged. For example:
foo: bar: one: two three: four
plus (later in the list)
foo: bar: one: 2 five: six
results in an effective input of
foo: bar: one: 2 three: four five: six
Note that the value of "foo" in the first document is not simply replaced with the value in the second, but its nested values are merged.
org.springframework.beans.factory.config.YamlPropertiesFactoryBean
Factory for java.util.Properties that reads from a YAML source, exposing a flat structure of String property values.
YAML is a nice human-readable format for configuration, and it has some useful hierarchical properties. It's more or less a superset of JSON, so it has a lot of similar features.
Note: All exposed values are of type
String
for access through the common
Properties#getProperty
method (e.g. in configuration property resolution through
PropertyResourceConfigurer#setProperties(Properties)
). If this is not desirable, use YamlMapFactoryBean instead.
The Properties created by this factory have nested paths for hierarchical objects, so for instance this YAML
environments: dev: url: http://dev.bar.com name: Developer Setup prod: url: http://foo.bar.com name: My Cool App
is transformed into these properties:
environments.dev.url=http://dev.bar.com environments.dev.name=Developer Setup environments.prod.url=http://foo.bar.com environments.prod.name=My Cool App
Lists are split as property keys with
[]
dereferencers, for example this YAML:
servers: - dev.bar.com - foo.bar.com
becomes properties like this:
servers[0]=dev.bar.com servers[1]=foo.bar.com
曾深爱过的沙滩裤 · org.mockito.Answers.get()Lorg/mockito/stubbing/Answer;:java.lang.NoSuchMethodError开发者社区 4 天前 |
微醺的荔枝 · Use org.mockito.internal.invocation.InvocationBuilder.Mockito.mock in Mockito with Examples | Lambda 4 天前 |
任性的小马驹 · 以Windows服务方式运行Java程序 4 天前 |
大力的烤面包 · 3d斗罗大陆禁图 - 百度 3 月前 |
冷静的勺子 · 美国女子“嫁给”聊天机器人 用《进击的巨人》给丈夫起名 6 月前 |