### Resource Bundle Content Example 1 Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/beans/context-introduction.adoc Example content for a resource bundle file named 'format.properties'. ```properties # in format.properties message=Alligators rock! ``` -------------------------------- ### Setup MockMvcHtmlUnitDriver with Pre-configured MockMvc (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/htmlunit/webdriver.adoc Configures the WebDriver using MockMvcHtmlUnitDriverBuilder with a pre-configured MockMvc instance. This Kotlin example demonstrates applying Spring Security to the MockMvc setup. ```kotlin val mockMvc: MockMvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build() driver = MockMvcHtmlUnitDriverBuilder .mockMvcSetup(mockMvc) // for illustration only - defaults to "" .contextPath("") // By default MockMvc is used for localhost only; // the following will use MockMvc for example.com and example.org as well .useMockMvcForHosts("example.com", "example.org") .build() ``` -------------------------------- ### Resource Bundle Content Example 2 Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/beans/context-introduction.adoc Example content for a resource bundle file named 'exceptions.properties'. ```properties # in exceptions.properties argument.required=The {0} argument is required. ``` -------------------------------- ### Resource Path Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/resources.adoc Illustrates a typical resource path within a package structure. ```text com/mycompany/package1/service-context.xml ``` -------------------------------- ### Example Profiling Output Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/aop/schema.adoc Sample output demonstrating the profiling results from the around advice. ```text StopWatch 'Profiling for 'Pengo' and '12': running time (millis) = 0 ----------------------------------------- ms % Task name ----------------------------------------- 00000 ? execution(getFoo) ``` -------------------------------- ### My Application Configuration Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/aot.adoc A basic example of an application context configuration using @Configuration classes. ```java package com.example; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class MyApplication { @Bean public MyService myService() { return new MyService(); } } ``` -------------------------------- ### Basic MockRestServiceServer Setup in Java Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/spring-mvc-test-client.adoc Demonstrates the basic setup of MockRestServiceServer with RestTemplate in Java. It configures the server to expect a request to '/greeting' and respond with a success status. ```java RestTemplate restTemplate = new RestTemplate(); MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build(); mockServer.expect(requestTo("/greeting")).andRespond(withSuccess()); // Test code that uses the above RestTemplate ... mockServer.verify(); ``` -------------------------------- ### Basic MockRestServiceServer Setup in Kotlin Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/spring-mvc-test-client.adoc Demonstrates the basic setup of MockRestServiceServer with RestTemplate in Kotlin. It configures the server to expect a request to '/greeting' and respond with a success status. ```kotlin val restTemplate = RestTemplate() val mockServer = MockRestServiceServer.bindTo(restTemplate).build() mockServer.expect(requestTo("/greeting")).andRespond(withSuccess()) // Test code that uses the above RestTemplate ... mockServer.verify() ``` -------------------------------- ### Java After Returning Advice Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/aop-api/advice.adoc A Java example of AfterReturningAdvice that counts successful method invocations. ```java public class CountingAfterReturningAdvice implements AfterReturningAdvice { private int count; public void afterReturning(Object returnValue, Method m, Object[] args, Object target) throws Throwable { ++count; } public int getCount() { return count; } } ``` -------------------------------- ### Create RouterFunction with Router DSL (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webmvc-functional.adoc Utilize the router DSL for a more concise way to define routes and their corresponding handler functions. This example demonstrates GET and POST routes. ```kotlin import org.springframework.web.servlet.function.router val repository: PersonRepository = ... val handler = PersonHandler(repository) val route = router { accept(APPLICATION_JSON).nest { GET("/person/{id}", handler::getPerson) GET("/person", handler::listPeople) } POST("/person", handler::createPerson) } class PersonHandler(private val repository: PersonRepository) { // ... fun listPeople(request: ServerRequest): ServerResponse { // ... } fun createPerson(request: ServerRequest): ServerResponse { // ... } fun getPerson(request: ServerRequest): ServerResponse { // ... } } ``` -------------------------------- ### Basic MockMvcHtmlUnitDriverBuilder Setup (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/htmlunit/webdriver.adoc Builds a WebDriver instance using MockMvcHtmlUnitDriverBuilder with a WebApplicationContext. ```kotlin lateinit var driver: WebDriver @BeforeEach fun setup(context: WebApplicationContext) { driver = MockMvcHtmlUnitDriverBuilder .webAppContextSetup(context) .build() } ``` -------------------------------- ### Perform GET Request and Retrieve String Body (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/integration/rest-clients.adoc Sets up a GET request, retrieves the response, and converts the body to a String. Use this for simple GET requests where only the response body as a String is needed. ```java String result = restClient.get() .uri("https://example.com") .retrieve() .body(String.class); System.out.println(result); ``` -------------------------------- ### JUnit 4 Integration Test Setup (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/support-classes.adoc Example of setting up a JUnit 4 integration test class using Spring's test rules in Kotlin. ```kotlin // Optionally specify a non-Spring Runner via @RunWith(...) @ContextConfiguration class IntegrationTest { @Rule val springMethodRule = SpringMethodRule() @Test fun testMethod() { // test logic... } companion object { @ClassRule val springClassRule = SpringClassRule() } } ``` -------------------------------- ### Perform GET Request and Retrieve String Body (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/integration/rest-clients.adoc Sets up a GET request, retrieves the response, and converts the body to a String. Use this for simple GET requests where only the response body as a String is needed. ```kotlin val result= restClient.get() .uri("https://example.com") .retrieve() .body() println(result); ``` -------------------------------- ### Counting MethodBeforeAdvice Example in Java Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/aop-api/advice.adoc An example of a before advice that counts method invocations. ```java public class CountingBeforeAdvice implements MethodBeforeAdvice { private int count; ``` -------------------------------- ### Basic MockMvcHtmlUnitDriverBuilder Setup (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/htmlunit/webdriver.adoc Builds a WebDriver instance using MockMvcHtmlUnitDriverBuilder with a WebApplicationContext. ```java WebDriver driver; @BeforeEach void setup(WebApplicationContext context) { driver = MockMvcHtmlUnitDriverBuilder .webAppContextSetup(context) .build(); } ``` -------------------------------- ### Missing Reflection Hint Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/aot.adoc This output shows an example of a test failure when a required reflection hint is missing, indicating the specific invocation and arguments that failed. ```txt org.springframework.docs.core.aot.hints.testing.SampleReflection performReflection INFO: Spring version: 6.2.0 Missing <"ReflectionHints"> for invocation with arguments ["org.springframework.core.SpringVersion", false, jdk.internal.loader.ClassLoaders$AppClassLoader@251a69d7]. Stacktrace: <"org.springframework.util.ClassUtils#forName, Line 284 io.spring.runtimehintstesting.SampleReflection#performReflection, Line 19 ``` -------------------------------- ### WebClient Setup with Pre-configured MockMvc Instance Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/htmlunit/mah.adoc Sets up a WebClient by first configuring a MockMvc instance separately and then supplying it to MockMvcWebClientBuilder. This provides full access to MockMvc capabilities. ```java MockMvc mockMvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build(); webClient = MockMvcWebClientBuilder .mockMvcSetup(mockMvc) // for illustration only - defaults to "" .contextPath("") // By default MockMvc is used for localhost only; // the following will use MockMvc for example.com and example.org as well .useMockMvcForHosts("example.com","example.org") .build(); ``` -------------------------------- ### Kotlin @BeforeTransaction Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/annotations/integration-spring/annotation-beforetransaction.adoc Use @BeforeTransaction to define logic that runs before a transaction starts in your test. ```kotlin @BeforeTransaction // <1> fun beforeTransaction() { // logic to be run before a transaction is started } ``` -------------------------------- ### WebClient Setup with Pre-configured MockMvc Instance (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/htmlunit/mah.adoc Sets up a WebClient by first configuring a MockMvc instance separately and then supplying it to MockMvcWebClientBuilder in Kotlin. This provides full access to MockMvc capabilities. ```kotlin val mockMvc = MockMvcBuilders .webAppContextSetup(context) .apply(springSecurity()) .build() webClient = MockMvcWebClientBuilder .mockMvcSetup(mockMvc) // for illustration only - defaults to "" .contextPath("") // By default MockMvc is used for localhost only; // the following will use MockMvc for example.com and example.org as well .useMockMvcForHosts("example.com", "example.org") .build() ``` -------------------------------- ### Java @BeforeTransaction Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/annotations/integration-spring/annotation-beforetransaction.adoc Use @BeforeTransaction to define logic that runs before a transaction starts in your test. ```java @BeforeTransaction // <1> void beforeTransaction() { // logic to be run before a transaction is started } ``` -------------------------------- ### Standalone MockMvc Setup with Expectations Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/hamcrest/expectations.adoc Demonstrates setting up a standalone MockMvc instance with common expectations for status and content type. ```kotlin standaloneSetup(SimpleController()) .alwaysExpect(status().isOk()) .alwaysExpect(content().contentType("application/json;charset=UTF-8")) .build() ``` -------------------------------- ### Argument Type Matching Examples (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/beans/dependencies/factory-method-injection.adoc Examples demonstrating how to specify argument types for method replacement. Shortened type names like 'String' or 'Str' can be used if they uniquely identify the type. ```java java.lang.String String Str ``` -------------------------------- ### Record Base Packages Scan Startup Step in Java Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/beans/context-introduction.adoc This Java snippet demonstrates how to create and record a startup step for base package scanning, including adding tag information. It uses a try-with-resources statement for automatic cleanup. ```java // create a startup step and start recording try (StartupStep scanPackages = getApplicationStartup().start("spring.context.base-packages.scan")) { // add tagging information to the current step scanPackages.tag("packages", () -> Arrays.toString(basePackages)); // perform the actual phase we're instrumenting this.scanner.scan(basePackages); } ``` -------------------------------- ### WebFlux @ResponseBody Method Example (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webflux/controller/ann-methods/responsebody.adoc Use @ResponseBody on a method to serialize its return value to the HTTP response body. This example shows a simple GET endpoint returning an Account object. ```java @GetMapping("/accounts/{id}") @ResponseBody public Account handle() { // ... } ``` -------------------------------- ### WebFlux @ResponseBody Method Example (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webflux/controller/ann-methods/responsebody.adoc Use @ResponseBody on a method to serialize its return value to the HTTP response body. This example shows a simple GET endpoint returning an Account object in Kotlin. ```kotlin @GetMapping("/accounts/{id}") @ResponseBody fun handle(): Account { // ... } ``` -------------------------------- ### Java Setter-Based DI Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/beans/dependencies/factory-collaborators.adoc A Java POJO demonstrating setter-based dependency injection for a MovieFinder. ```java public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder; // a setter method so that the Spring container can inject a MovieFinder public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // business logic that actually uses the injected MovieFinder is omitted... } ``` -------------------------------- ### Configure JMX Notification Listener Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/integration/jmx/notifications.adoc Configures an MBeanExporter to use a NotificationListenerBean for receiving JMX notifications. This example shows basic listener setup. ```xml bean:name=testBean1 ``` -------------------------------- ### Record Base Packages Scan Startup Step in Kotlin Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/beans/context-introduction.adoc This Kotlin snippet shows how to create and record a startup step for base package scanning, including adding tag information. It utilizes a try-with-resources statement for automatic resource management. ```kotlin // create a startup step and start recording try (val scanPackages = getApplicationStartup().start("spring.context.base-packages.scan")) { // add tagging information to the current step scanPackages.tag("packages", () -> Arrays.toString(basePackages)); // perform the actual phase we're instrumenting this.scanner.scan(basePackages); } ``` -------------------------------- ### Basic WebClient Setup with MockMvcWebClientBuilder (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/htmlunit/mah.adoc Sets up a WebClient using MockMvcWebClientBuilder based on the WebApplicationContext in Kotlin. This is the simplest approach for integrating MockMvc with HtmlUnit. ```kotlin lateinit var webClient: WebClient @BeforeEach fun setup(context: WebApplicationContext) { webClient = MockMvcWebClientBuilder .webAppContextSetup(context) .build() } ``` -------------------------------- ### Java Fictitious Transactional Test Setup Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/tx.adoc A Java example demonstrating the use of @SpringJUnitConfig, @Transactional, @Commit, and @BeforeTransaction annotations for integration testing. ```java @SpringJUnitConfig @Transactional(transactionManager = "txMgr") @Commit class FictitiousTransactionalTest { @BeforeTransaction void verifyInitialDatabaseState() { ``` -------------------------------- ### Method-level @ResponseBody in Java Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webmvc/mvc-controller/ann-methods/responsebody.adoc Use @ResponseBody on a method to serialize its return value to the response body. This example shows a GET mapping for retrieving an Account. ```java @GetMapping("/accounts/{id}") @ResponseBody public Account handle() { // ... } ``` -------------------------------- ### JUnit 4 Integration Test Setup Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/support-classes.adoc Example of setting up a JUnit 4 integration test class using Spring's test rules. ```java // Optionally specify a non-Spring Runner via @RunWith(...) @ContextConfiguration public class IntegrationTest { @ClassRule public static final SpringClassRule springClassRule = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); @Test public void testMethod() { // test logic... } } ``` -------------------------------- ### Kotlin @Repeat Annotation Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/annotations/integration-junit4.adoc Use the @Repeat annotation to specify the number of times a test method should be executed. This includes setup and teardown phases. ```kotlin @Repeat(10) // <1> @Test fun testProcessRepeatedly() { // ... } ``` -------------------------------- ### Java @Repeat Annotation Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/annotations/integration-junit4.adoc Use the @Repeat annotation to specify the number of times a test method should be executed. This includes setup and teardown phases. ```java @Repeat(10) // <1> @Test public void testProcessRepeatedly() { // ... } ``` -------------------------------- ### Basic WebClient Setup with MockMvcWebClientBuilder Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/htmlunit/mah.adoc Sets up a WebClient using MockMvcWebClientBuilder based on the WebApplicationContext. This is the simplest approach for integrating MockMvc with HtmlUnit. ```java WebClient webClient; @BeforeEach void setup(WebApplicationContext context) { webClient = MockMvcWebClientBuilder .webAppContextSetup(context) .build(); } ``` -------------------------------- ### Kotlin Transactional Test Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/tx.adoc Demonstrates a transactional test in Kotlin, showing how to flag for commit, end, and start transactions, and assert database state. ```kotlin fun transactionalTest() { // assert initial state in test database: assertNumUsers(2) deleteFromTables("user") // changes to the database will be committed! TestTransaction.flagForCommit() TestTransaction.end() assertFalse(TestTransaction.isActive()) assertNumUsers(0) TestTransaction.start() // perform other actions against the database that will // be automatically rolled back after the test completes... } protected fun assertNumUsers(expected: Int) { assertEquals("Number of rows in the [user] table.", expected, countRowsInTable("user")) } } ``` -------------------------------- ### Around Advice Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/aop/ataspectj/advice.adoc Demonstrates a basic around advice that profiles method execution by timing the proceed() call. It returns the result of the proceed() call. ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.ProceedingJoinPoint; @Aspect public class AroundExample { @Around("execution(* com.xyz..service.*.*(..))") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable { // start stopwatch Object retVal = pjp.proceed(); // stop stopwatch return retVal; } } ``` ```kotlin import org.aspectj.lang.annotation.Aspect import org.aspectj.lang.annotation.Around import org.aspectj.lang.ProceedingJoinPoint @Aspect class AroundExample { @Around("execution(* com.xyz..service.*.*(..))") fun doBasicProfiling(pjp: ProceedingJoinPoint): Any? { // start stopwatch val retVal = pjp.proceed() // stop stopwatch return retVal } } ``` -------------------------------- ### Method-level @ResponseBody in Kotlin Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webmvc/mvc-controller/ann-methods/responsebody.adoc Use @ResponseBody on a method to serialize its return value to the response body. This example shows a GET mapping for retrieving an Account in Kotlin. ```kotlin @GetMapping("/accounts/{id}") @ResponseBody fun handle(): Account { // ... } ``` -------------------------------- ### IntroductionAdvisor and IntroductionInfo Interfaces Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/aop-api/advice.adoc Defines interfaces for Introduction Advisors, which manage class filtering and introduced interfaces. IntroductionInfo specifies how to retrieve the interfaces to be introduced. ```java public interface IntroductionAdvisor extends Advisor, IntroductionInfo { ClassFilter getClassFilter(); void validateInterfaces() throws IllegalArgumentException; } public interface IntroductionInfo { Class[] getInterfaces(); } ``` -------------------------------- ### Query First Row (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/data-access/r2dbc.adoc Example of querying the first row from a table in Kotlin, returning a Map. It uses fetch().awaitSingle() to get the single result. ```kotlin val first = client.sql("SELECT id, name FROM person").fetch().awaitSingle() ``` -------------------------------- ### LockMixinAdvisor Class Example (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/aop-api/advice.adoc Presents the Kotlin version of LockMixinAdvisor, demonstrating its initialization with a LockMixin instance and the Lockable interface using concise syntax. ```kotlin class LockMixinAdvisor : DefaultIntroductionAdvisor(LockMixin(), Lockable::class.java) ``` -------------------------------- ### Create RouterFunction with RouterBuilder (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webmvc-functional.adoc Use RouterFunctions.route() to build a router that maps HTTP methods and paths to handler functions. This example shows GET and POST mappings. ```java import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.web.servlet.function.RequestPredicates.*; import static org.springframework.web.servlet.function.RouterFunctions.route; PersonRepository repository = ... PersonHandler handler = new PersonHandler(repository); RouterFunction route = route() .GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) .GET("/person", accept(APPLICATION_JSON), handler::listPeople) .POST("/person", handler::createPerson) .build(); public class PersonHandler { // ... public ServerResponse listPeople(ServerRequest request) { // ... } public ServerResponse createPerson(ServerRequest request) { // ... } public ServerResponse getPerson(ServerRequest request) { // ... } } ``` -------------------------------- ### Query First Row (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/data-access/r2dbc.adoc Example of querying the first row from a table, returning a Map. It uses fetch().first() to get the first result. ```java Mono> first = client.sql("SELECT id, name FROM person").fetch().first(); ``` -------------------------------- ### Basic Context Hierarchy Configuration in Kotlin Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/ctx-management/hierarchies.adoc Demonstrates the basic setup for defining context hierarchies for SOAP and REST web services using Kotlin. ```kotlin @ExtendWith(SpringExtension::class) @WebAppConfiguration @ContextConfiguration("file:src/main/webapp/WEB-INF/applicationContext.xml") abstract class AbstractWebTests @ContextHierarchy(ContextConfiguration("/spring/soap-ws-config.xml")) class SoapWebServiceTests : AbstractWebTests() @ContextHierarchy(ContextConfiguration("/spring/rest-ws-config.xml")) class RestWebServiceTests : AbstractWebTests() ``` -------------------------------- ### Configure Pivotal Remote Source: https://github.com/spring-projects/spring-framework/wiki/Manually-merging-pull-requests Example output showing how the 'pivotal' remote should be configured for fetching and pushing. ```shell $> git remote show pivotal * remote pivotal Fetch URL: git@github.com:spring-projects/spring-framework.git Push URL: git@github.com:spring-projects/spring-framework.git ``` -------------------------------- ### Basic Context Hierarchy Configuration Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/ctx-management/hierarchies.adoc Demonstrates the basic setup for defining context hierarchies for SOAP and REST web services using Java. ```java @ContextHierarchy(@ContextConfiguration("/spring/soap-ws-config.xml")) public class SoapWebServiceTests extends AbstractWebTests {} @ContextHierarchy(@ContextConfiguration("/spring/rest-ws-config.xml")) public class RestWebServiceTests extends AbstractWebTests {} ``` -------------------------------- ### Annotation Use-Site Targets for Bean Validation Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/languages/kotlin/annotations.adoc Provides examples of annotation use-site targets for bean validation on properties or constructor parameters in Kotlin, such as `@field:NotNull` or `@get:Size`. ```kotlin @field:NotNull @get:Size(min=5, max=15) ``` -------------------------------- ### Programmatically Build Container with register() (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/beans/java/instantiating-container.adoc Instantiate AnnotationConfigApplicationContext with a no-arg constructor and use register() to add configuration classes programmatically. Call refresh() to complete the setup. ```java public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig.class, OtherConfig.class); ctx.register(AdditionalConfig.class); ctx.refresh(); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); } ``` -------------------------------- ### Kotlin SimpleJdbcCall for Stored Procedure Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/data-access/jdbc/simple.adoc Kotlin example demonstrating the setup and execution of a stored procedure using SimpleJdbcCall. It configures the procedure name, result set mapping, and executes the call with an empty parameter map. ```kotlin class JdbcActorDao(dataSource: DataSource) : ActorDao { private val procReadAllActors = SimpleJdbcCall(JdbcTemplate(dataSource).apply { isResultsMapCaseInsensitive = true }).withProcedureName("read_all_actors") .returningResultSet("actors", BeanPropertyRowMapper.newInstance(Actor::class.java)) fun getActorsList(): List { val m = procReadAllActors.execute(mapOf()) return m["actors"] as List } // ... additional methods } ``` -------------------------------- ### Java SimpleJdbcCall for Stored Procedure Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/data-access/jdbc/simple.adoc Java example demonstrating the setup and execution of a stored procedure using SimpleJdbcCall. It configures the procedure name, result set mapping, and executes the call with an empty parameter map. ```java private SimpleJdbcCall procReadAllActors; public void setDataSource(DataSource dataSource) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.setResultsMapCaseInsensitive(true); this.procReadAllActors = new SimpleJdbcCall(jdbcTemplate) .withProcedureName("read_all_actors") .returningResultSet("actors", BeanPropertyRowMapper.newInstance(Actor.class)); } public List getActorsList() { Map m = procReadAllActors.execute(new HashMap(0)); return (List) m.get("actors"); } // ... additional methods } ``` -------------------------------- ### Integration Test Setup with Multiple Configurations (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/ctx-management/env-profiles.adoc Sets up an integration test using multiple configuration classes and activates the 'dev' profile. ```java @SpringJUnitConfig({ TransferServiceConfig.class, StandaloneDataConfig.class, JndiDataConfig.class, DefaultDataConfig.class}) @ActiveProfiles("dev") class TransferServiceTest { @Autowired TransferService transferService; @Test void testTransferService() { // test the transferService } } ``` -------------------------------- ### PersonForm Model with Bean Validation Constraints (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/validation/beanvalidation.adoc Adds Bean Validation constraints (@get:NotNull, @get:Size, @get:Min) to the PersonForm model properties in Kotlin. ```kotlin class PersonForm( @get:NotNull @get:Size(max=64) private val name: String, @get:Min(0) private val age: Int ) ``` -------------------------------- ### Build URI with DefaultUriBuilderFactory (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/partials/web/web-uris.adoc Demonstrates building a URI using DefaultUriBuilderFactory with query parameters and path variables. ```java String baseUrl = "https://example.com"; DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(baseUrl); URI uri = uriBuilderFactory.uriString("/hotels/{hotel}") .queryParam("q", "{q}") .build("Westin", "123"); ``` -------------------------------- ### Minimal Java Class for Creating a Table Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/data-access/jdbc/core.adoc Demonstrates the minimal setup required for a Java class to create a table using `DataSource` and `JdbcTemplate`. Includes necessary imports. ```java import javax.sql.DataSource; ``` -------------------------------- ### Default Convention-Based Configuration Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/ctx-management/web.adoc Demonstrates default convention-based configuration for loading a WebApplicationContext and detecting configuration files or classes. ```java @ExtendWith(SpringExtension.class) // defaults to "file:src/main/webapp" @WebAppConfiguration // detects "WacTests-context.xml" in the same package // or static nested @Configuration classes @ContextConfiguration class WacTests { //... } ``` ```kotlin @ExtendWith(SpringExtension::class) // defaults to "file:src/main/webapp" @WebAppConfiguration // detects "WacTests-context.xml" in the same package // or static nested @Configuration classes @ContextConfiguration class WacTests { //... } ``` -------------------------------- ### Populating Reactor Context for WebClient Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webflux-webclient/client-context.adoc Demonstrates how to build a WebClient and use `contextWrite` to populate the Reactor Context. This context will propagate to subsequent operations like `flatMap`. ```java WebClient client = WebClient.builder() .filter((request, next) -> Mono.deferContextual(contextView -> { String value = contextView.get("foo"); // ... })) .build(); client.get().uri("https://example.org/") .retrieve() .bodyToMono(String.class) .flatMap(body -> { // perform nested request (context propagates automatically)... }) .contextWrite(context -> context.put("foo", ...)); ``` -------------------------------- ### Kotlin @DateTimeFormat Annotation Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/validation/format.adoc Example of using the @DateTimeFormat annotation with ISO.DATE on a Kotlin Date property. ```kotlin class MyModel( @DateTimeFormat(iso=ISO.DATE) private val date: Date ) ``` -------------------------------- ### Building URI Links with UriComponentsBuilder (Full URI) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webflux/uri-building.adoc Illustrates building a complete URI with scheme, host, port, path, and query parameters using `UriComponentsBuilder`. ```java UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); builder.scheme("https").host("example.com").port(8080).path("/hotels/{hotel}/bookings/{booking}"); builder.query("toDate={date}"); URI uri = builder.buildAndExpand("42", "10", "2024-12-31").encode().toUri(); System.out.println(uri); // Output: "https://example.com:8080/hotels/42/bookings/10?toDate=2024-12-31" ``` -------------------------------- ### Java @DateTimeFormat Annotation Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/validation/format.adoc Example of using the @DateTimeFormat annotation with ISO.DATE on a Java Date field. ```java public class MyModel { @DateTimeFormat(iso=ISO.DATE) private Date date; } ``` -------------------------------- ### Bootstrap Java Application Context Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/beans/java/composing-configuration-classes.adoc Demonstrates how to bootstrap an `ApplicationContext` using an `AnnotationConfigApplicationContext` in Java. ```java public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); TransferService transferService = ctx.getBean(TransferService.class); // ... } ``` -------------------------------- ### Build URI with DefaultUriBuilderFactory (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/partials/web/web-uris.adoc Demonstrates building a URI using DefaultUriBuilderFactory with query parameters and path variables. ```kotlin val baseUrl = "https://example.com" val uriBuilderFactory = DefaultUriBuilderFactory(baseUrl) val uri = uriBuilderFactory.uriString("/hotels/{hotel}") .queryParam("q", "{q}") .build("Westin", "123") ``` -------------------------------- ### Integration Test Setup with Multiple Configurations (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/ctx-management/env-profiles.adoc Sets up an integration test in Kotlin using multiple configuration classes and activates the 'dev' profile. ```kotlin @SpringJUnitConfig( TransferServiceConfig::class, StandaloneDataConfig::class, JndiDataConfig::class, DefaultDataConfig::class) @ActiveProfiles("dev") class TransferServiceTest { @Autowired lateinit var transferService: TransferService @Test fun testTransferService() { // test the transferService } } ``` -------------------------------- ### Transactional Test Setup in Kotlin Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/tx.adoc Demonstrates the setup for a transactional test class in Kotlin using Spring JUnit. ```kotlin @SpringJUnitConfig @Transactional(transactionManager = "txMgr") @Commit class FictitiousTransactionalTest { @BeforeTransaction fun verifyInitialDatabaseState() { // logic to verify the initial state before a transaction is started } @BeforeEach fun setUpTestDataWithinTransaction() { // set up test data within the transaction } @Test // overrides the class-level @Commit setting @Rollback fun modifyDatabaseWithinTransaction() { // logic which uses the test data and modifies database state } @AfterEach fun tearDownWithinTransaction() { // run "tear down" logic within the transaction } @AfterTransaction fun verifyFinalDatabaseState() { // logic to verify the final state after transaction has rolled back } } ``` -------------------------------- ### Transactional Test Setup in Java Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/tx.adoc Demonstrates the setup for a transactional test class in Java using Spring JUnit. ```java @SpringJUnitConfig @Transactional(transactionManager = "txMgr") @Commit class FictitiousTransactionalTest { @BeforeTransaction void verifyInitialDatabaseState() { // logic to verify the initial state before a transaction is started } @BeforeEach void setUpTestDataWithinTransaction() { // set up test data within the transaction } @Test // overrides the class-level @Commit setting @Rollback void modifyDatabaseWithinTransaction() { // logic which uses the test data and modifies database state } @AfterEach void tearDownWithinTransaction() { // run "tear down" logic within the transaction } @AfterTransaction void verifyFinalDatabaseState() { // logic to verify the final state after transaction has rolled back } } ``` -------------------------------- ### Create DatabaseClient with ConnectionFactory Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/data-access/r2dbc.adoc Demonstrates the basic creation of a `DatabaseClient` instance using a provided `ConnectionFactory`. This is the starting point for R2DBC operations. ```java DatabaseClient client = DatabaseClient.create(connectionFactory); ``` ```kotlin val client = DatabaseClient.create(connectionFactory) ``` -------------------------------- ### Get Cookie Value in Java Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webmvc/mvc-controller/ann-methods/cookievalue.adoc Binds the value of the 'JSESSIONID' cookie to a String method argument. Requires a GET mapping. ```java @GetMapping("/demo") public void handle(@CookieValue("JSESSIONID") String cookie) { //... } ``` -------------------------------- ### FileSystemXmlApplicationContext with file: Prefix (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/resources.adoc Initializes FileSystemXmlApplicationContext using a 'file:' URL prefix to ensure resources are loaded as UrlResource. ```java // force this FileSystemXmlApplicationContext to load its definition via a UrlResource ApplicationContext ctx = new FileSystemXmlApplicationContext("file:///conf/context.xml"); ``` -------------------------------- ### Basic Hello World Controller in Kotlin Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webflux/controller.adoc A simple Kotlin @RestController that handles a GET request to '/hello' and returns a String response. ```kotlin @RestController class HelloController { @GetMapping("/hello") fun handle() = "Hello WebFlux" } ``` -------------------------------- ### Client SUBSCRIBE Frame Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/websocket/stomp/overview.adoc Example of a STOMP SUBSCRIBE frame used by a client to subscribe to a topic for stock quotes. ```text SUBSCRIBE id:sub-1 destination:/topic/price.stock.* ^@ ``` -------------------------------- ### FileSystemXmlApplicationContext Initialization (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/resources.adoc Initializes FileSystemXmlApplicationContext with a relative path in Kotlin. This is a common way to load configuration files. ```kotlin val ctx = FileSystemXmlApplicationContext("conf/context.xml") ``` -------------------------------- ### Get Cookie Value in Kotlin Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webmvc/mvc-controller/ann-methods/cookievalue.adoc Binds the value of the 'JSESSIONID' cookie to a String method argument in Kotlin. Requires a GET mapping. ```kotlin @GetMapping("/demo") fun handle(@CookieValue("JSESSIONID") cookie: String): Unit { //... } ``` -------------------------------- ### Bootstrap Kotlin Application Context Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/beans/java/composing-configuration-classes.adoc Demonstrates how to bootstrap an `ApplicationContext` using an `AnnotationConfigApplicationContext` in Kotlin. ```kotlin import org.springframework.beans.factory.getBean fun main() { val ctx = AnnotationConfigApplicationContext(AppConfig::class.java) val transferService = ctx.getBean() // ... } ``` -------------------------------- ### Perform GET Request with Query Parameter in URI Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/hamcrest/requests.adoc Demonstrates performing a GET request with a query parameter embedded in the URI template. ```java mockMvc.perform(get("/hotels?thing={thing}", "somewhere")); ``` -------------------------------- ### RouterFunction DSL Builder Example Source: https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-5.1-Release-Notes Demonstrates the DSL-style builder for RouterFunction without static imports. This is useful for defining routing configurations in a more fluent manner. ```java RouterFunction routes = route( GET("/foo/bar"), request -> ServerResponse.ok().bodyValue("bar")) .andRoute(POST("/foo/bar"), request -> ServerResponse.ok().bodyValue("bar")); ``` -------------------------------- ### Server MESSAGE Frame Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/websocket/stomp/overview.adoc Example of a STOMP MESSAGE frame sent by a server to broadcast a stock quote to a subscribed client. ```text MESSAGE message-id:nxahklf6-1 subscription:sub-1 destination:/topic/price.stock.MMM {"ticker":"MMM","price":129.45}^@ ``` -------------------------------- ### FileSystemXmlApplicationContext Initialization (Java) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/core/resources.adoc Initializes FileSystemXmlApplicationContext with a relative path. This is a common way to load configuration files. ```java ApplicationContext ctx = new FileSystemXmlApplicationContext("conf/context.xml"); ``` -------------------------------- ### Client SEND Frame Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/websocket/stomp/overview.adoc Example of a STOMP SEND frame used by a client to send a trade request with JSON payload. ```text SEND destination:/queue/trade content-type:application/json content-length:44 {"action":"BUY","ticker":"MMM","shares":44}^@ ``` -------------------------------- ### RESTful Service Multipart Request Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webmvc/mvc-controller/ann-methods/multipart-forms.adoc Example of a multipart/mixed request for a RESTful service, including JSON metadata and file data. ```text POST /someUrl Content-Type: multipart/mixed --edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp Content-Disposition: form-data; name="meta-data" Content-Type: application/json; charset=UTF-8 Content-Transfer-Encoding: 8bit { "name": "value" } --edt7Tfrdusa7r3lNQc79vXuhIIMlatb7PQg7Vp Content-Disposition: form-data; name="file-data"; filename="file.properties" Content-Type: text/xml Content-Transfer-Encoding: 8bit ... File Data ... ``` -------------------------------- ### Kotlin @BeforeTransaction Method Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/tx.adoc Example of a @BeforeTransaction method in Kotlin, optionally accepting an autowired DataSource to verify initial database state. ```kotlin @BeforeTransaction fun verifyInitialDatabaseState(@Autowired dataSource: DataSource) { // Use the DataSource to verify the initial state before a transaction is started } ``` -------------------------------- ### Create WebClient with Codecs (Kotlin) Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webflux-webclient/client-builder.adoc Builds a WebClient instance in Kotlin, allowing for codec configuration. Use when custom codec settings are required. ```kotlin val webClient = WebClient.builder() .codecs { configurer -> ... } .build() ``` -------------------------------- ### Serve Resources from a Root Location with Kotlin Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/web/webflux-functional.adoc Routes requests matching '/resources/**' to files located in the 'public-resources/' directory. ```kotlin val location = FileUrlResource("public-resources/") val resources = router { resources("/resources/**", location) } ``` -------------------------------- ### Java @BeforeTransaction Method Example Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/testcontext-framework/tx.adoc Example of a @BeforeTransaction method in Java, optionally accepting an autowired DataSource to verify initial database state. ```java @BeforeTransaction void verifyInitialDatabaseState(@Autowired DataSource dataSource) { // Use the DataSource to verify the initial state before a transaction is started } ``` -------------------------------- ### Getting Direct Access to MvcResult Source: https://github.com/spring-projects/spring-framework/blob/main/framework-docs/modules/ROOT/pages/testing/mockmvc/hamcrest/expectations.adoc Append `.andReturn()` to get direct access to the `MvcResult` object, allowing verification of aspects not covered by standard matchers. ```java MvcResult mvcResult = mockMvc.perform(post("/persons")).andExpect(status().isOk()).andReturn(); // ... ```