### Programmatic Transaction Management Example Source: https://docs.spring.io/spring-framework/reference/6.2/testing/testcontext-framework/tx.html Demonstrates starting, ending, flagging for commit, and checking the active state of test-managed transactions. Changes flagged for commit will be committed, while others will be rolled back. ```java @ContextConfiguration(classes = TestConfig.class) public class ProgrammaticTransactionManagementTests extends AbstractTransactionalJUnit4SpringContextTests { @Test public void 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 void assertNumUsers(int expected) { assertEquals("Number of rows in the [user] table.", expected, countRowsInTable("user")); } } ``` -------------------------------- ### Basic MockRestServiceServer Setup (Kotlin) Source: https://docs.spring.io/spring-framework/reference/6.2/testing/spring-mvc-test-client.html Demonstrates the basic setup of MockRestServiceServer to mock a RestTemplate request and response in Kotlin. Use this for simple client-side testing. ```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() ``` -------------------------------- ### Programmatic Transaction Management Example (Kotlin) Source: https://docs.spring.io/spring-framework/reference/6.2/testing/testcontext-framework/tx.html Demonstrates starting, ending, flagging for commit, and checking the active state of test-managed transactions in Kotlin. Changes flagged for commit will be committed, while others will be rolled back. ```kotlin @ContextConfiguration(classes = [TestConfig::class]) class ProgrammaticTransactionManagementTests : AbstractTransactionalJUnit4SpringContextTests() { @Test 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")) } } ``` -------------------------------- ### Argument Type Matching Examples Source: https://docs.spring.io/spring-framework/reference/6.2/core/beans/dependencies/factory-method-injection.html Examples demonstrating how to specify argument types for method replacement in XML. Short, unambiguous substrings of fully qualified type names are sufficient. ```xml java.lang.String String Str ``` -------------------------------- ### Basic MockRestServiceServer Setup (Java) Source: https://docs.spring.io/spring-framework/reference/6.2/testing/spring-mvc-test-client.html Demonstrates the basic setup of MockRestServiceServer to mock a RestTemplate request and response in Java. Use this for simple client-side testing. ```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(); ``` -------------------------------- ### Configure GET Request URI with Template Variable (Java) Source: https://docs.spring.io/spring-framework/reference/6.2/integration/rest-clients.html Example of configuring a GET request URI using a string with a URI template variable and an integer value in Java. ```java int id = 42; restClient.get() .uri("https://example.com/orders/{id}", id) // ... ``` -------------------------------- ### Kotlin Startup Step Instrumentation Source: https://docs.spring.io/spring-framework/reference/6.2/core/beans/context-introduction.html Example of creating and tagging a startup step in Kotlin for application context base package scanning. ```kotlin val scanPackages = getApplicationStartup().start("spring.context.base-packages.scan") scanPackages.tag("packages", () -> Arrays.toString(basePackages)) this.scanner.scan(basePackages) scanPackages.end() ``` -------------------------------- ### Java @BeforeTransaction Example Source: https://docs.spring.io/spring-framework/reference/6.2/testing/annotations/integration-spring/annotation-beforetransaction.html Use this Java snippet to define a method that runs before a transaction is started. The method must be void and can be non-public. ```java @BeforeTransaction void beforeTransaction() { // logic to be run before a transaction is started } ``` -------------------------------- ### Java Startup Step Instrumentation Source: https://docs.spring.io/spring-framework/reference/6.2/core/beans/context-introduction.html Example of creating and tagging a startup step in Java for application context base package scanning. ```java StartupStep scanPackages = getApplicationStartup().start("spring.context.base-packages.scan"); scanPackages.tag("packages", () -> Arrays.toString(basePackages)); this.scanner.scan(basePackages); scanPackages.end(); ``` -------------------------------- ### Basic Context Hierarchy Configuration Source: https://docs.spring.io/spring-framework/reference/6.2/testing/testcontext-framework/ctx-management/hierarchies.html Demonstrates a simple context hierarchy setup using @ContextHierarchy with XML configuration files. ```java @ContextHierarchy(ContextConfiguration("/spring/soap-ws-config.xml")) class SoapWebServiceTests : AbstractWebTests() ``` ```java @ContextHierarchy(ContextConfiguration("/spring/rest-ws-config.xml")) class RestWebServiceTests : AbstractWebTests() ``` -------------------------------- ### Build WebClient with Pre-configured MockMvc Source: https://docs.spring.io/spring-framework/reference/6.2/testing/mockmvc/htmlunit/mah.html Sets up a WebClient by first configuring a MockMvc instance separately and then supplying it to MockMvcWebClientBuilder. This provides full MockMvc power. ```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 // Not possible in Kotlin until {kotlin-issues}/KT-22208 is fixed ``` -------------------------------- ### Basic After Throwing Advice (Java) Source: https://docs.spring.io/spring-framework/reference/6.2/core/aop/ataspectj/advice.html Use @AfterThrowing to run advice when a matched method execution exits by throwing an exception. This example shows a basic setup without specific exception handling. ```java import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.AfterThrowing; @Aspect public class AfterThrowingExample { @AfterThrowing("execution(* com.xyz.dao.*.*(..))") public void doRecoveryActions() { // ... } } ``` -------------------------------- ### Kotlin SimpleJdbcCall for Stored Function Source: https://docs.spring.io/spring-framework/reference/6.2/data-access/jdbc/simple.html Illustrates the Kotlin equivalent of using SimpleJdbcCall to execute a stored function. It covers similar setup steps as the Java example, including JdbcTemplate configuration and function execution. ```kotlin class JdbcActorDao(dataSource: DataSource) : ActorDao { private val jdbcTemplate = JdbcTemplate(dataSource).apply { isResultsMapCaseInsensitive = true } private val funcGetActorName = SimpleJdbcCall(jdbcTemplate) .withFunctionName("get_actor_name") fun getActorName(id: Long): String { val source = MapSqlParameterSource().addValue("in_id", id) return funcGetActorName.executeFunction(String::class.java, source) } // ... additional methods } ``` -------------------------------- ### Kotlin Implementation for Introduction Advice Source: https://docs.spring.io/spring-framework/reference/6.2/core/aop/schema.html The Kotlin method that implements the logic for the introduction advice. It is called when the advised method is executed. ```kotlin fun recordUsage(usageTracked: UsageTracked) { usageTracked.incrementUseCount() } ``` -------------------------------- ### Basic After Throwing Advice (Kotlin) Source: https://docs.spring.io/spring-framework/reference/6.2/core/aop/ataspectj/advice.html Use @AfterThrowing to run advice when a matched method execution exits by throwing an exception. This Kotlin example shows a basic setup without specific exception handling. ```kotlin import org.aspectj.lang.annotation.Aspect import org.aspectj.lang.annotation.AfterThrowing @Aspect class AfterThrowingExample { @AfterThrowing("execution(* com.xyz.dao.*.*(..))") fun doRecoveryActions() { // ... } } ``` -------------------------------- ### Example Message in format.properties Source: https://docs.spring.io/spring-framework/reference/6.2/core/beans/context-introduction.html A sample message entry for the 'format' resource bundle, demonstrating how to define a key-value pair for message retrieval. ```properties message=Alligators rock! ``` -------------------------------- ### Get WebApplicationContext using FacesContextUtils Source: https://docs.spring.io/spring-framework/reference/6.2/web/integration.html This example demonstrates how to retrieve the Spring WebApplicationContext using FacesContextUtils by passing the current FacesContext instance. This is useful for explicitly accessing Spring beans within a JSF application. ```java ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()); ``` -------------------------------- ### Initialize Database with SQL Scripts Source: https://docs.spring.io/spring-framework/reference/6.2/data-access/jdbc/initializing-datasource.html Use this snippet to run SQL scripts for creating schema and populating test data. Supports Ant-style resource patterns for script locations. ```xml ``` -------------------------------- ### Java Around Advice Example Source: https://docs.spring.io/spring-framework/reference/6.2/core/aop/ataspectj/advice.html Demonstrates a basic around advice in Java that profiles method execution. It invokes proceed() to run the advised method and returns its result. ```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; } } ``` -------------------------------- ### Define HTTP Service Interface with Type-Level @HttpExchange Source: https://docs.spring.io/spring-framework/reference/6.2/integration/rest-clients.html Apply @HttpExchange at the interface level to set common attributes like URL, accept, and content types for all methods. This example includes methods for getting and updating a repository. ```java @HttpExchange(url = "/repos/{owner}/{repo}", accept = "application/vnd.github.v3+json") public interface RepositoryService { @GetExchange Repository getRepository(@PathVariable String owner, @PathVariable String repo); @PatchExchange(contentType = MediaType.APPLICATION_FORM_URLENCODED_VALUE) void updateRepository(@PathVariable String owner, @PathVariable String repo, @RequestParam String name, @RequestParam String description, @RequestParam String homepage); } ``` -------------------------------- ### Basic @Configuration and @Bean in Kotlin Source: https://docs.spring.io/spring-framework/reference/6.2/core/beans/java/basic-concepts.html Demonstrates the equivalent of the Java configuration using Kotlin. This shows how to define beans in a concise manner with Kotlin. ```kotlin @Configuration class AppConfig { @Bean fun myService(): MyServiceImpl { return MyServiceImpl() } } ``` -------------------------------- ### Client SEND Frame Example Source: https://docs.spring.io/spring-framework/reference/6.2/web/websocket/stomp/overview.html A client-side STOMP frame example for sending a trade request to the server. ```text SEND destination:/queue/trade content-type:application/json content-length:44 {"action":"BUY","ticker":"MMM","shares",44}^@ ``` -------------------------------- ### IntroductionAdvisor and IntroductionInfo Interfaces Source: https://docs.spring.io/spring-framework/reference/6.2/core/aop-api/advice.html Defines the advisor for introduction advice, including class filtering and interface information. ```java public interface IntroductionAdvisor extends Advisor, IntroductionInfo { ClassFilter getClassFilter(); void validateInterfaces() throws IllegalArgumentException; } public interface IntroductionInfo { Class[] getInterfaces(); } ``` -------------------------------- ### Client SUBSCRIBE Frame Example Source: https://docs.spring.io/spring-framework/reference/6.2/web/websocket/stomp/overview.html A client-side STOMP frame example for subscribing to a topic to receive stock quotes. ```text SUBSCRIBE id:sub-1 destination:/topic/price.stock.* ^@ ``` -------------------------------- ### Setup MockMvcWebClientBuilder Source: https://docs.spring.io/spring-framework/reference/6.2/testing/mockmvc/htmlunit/mah.html Create an HtmlUnit WebClient that integrates with MockMvc. This setup is used for testing web application contexts. ```java WebClient webClient; @BeforeEach void setup(WebApplicationContext context) { webClient = MockMvcWebClientBuilder .webAppContextSetup(context) .build(); } ``` ```kotlin lateinit var webClient: WebClient @BeforeEach fun setup(context: WebApplicationContext) { webClient = MockMvcWebClientBuilder .webAppContextSetup(context) .build() } ``` -------------------------------- ### Using for Concise List Creation Source: https://docs.spring.io/spring-framework/reference/6.2/core/appendix/xsd-schemas.html This example shows a more concise way to create a java.util.List using the element. It directly defines the list values. ```xml pechorin@hero.org raskolnikov@slums.org stavrogin@gov.org porfiry@gov.org ``` -------------------------------- ### Server MESSAGE Frame Example Source: https://docs.spring.io/spring-framework/reference/6.2/web/websocket/stomp/overview.html A server-side STOMP frame example for broadcasting a stock quote message to a subscribed client. ```text MESSAGE message-id:nxahklf6-1 subscription:sub-1 destination:/topic/price.stock.MMM {"ticker":"MMM","price":129.45}^@ ``` -------------------------------- ### Kotlin TaskExecutor Example Source: https://docs.spring.io/spring-framework/reference/6.2/integration/scheduling.html Kotlin version of the TaskExecutor example. Uses a data class for the message and injects TaskExecutor via constructor. ```kotlin class TaskExecutorExample(private val taskExecutor: TaskExecutor) { private inner class MessagePrinterTask(private val message: String) : Runnable { override fun run() { println(message) } } fun printMessages() { for (i in 0..24) { taskExecutor.execute( MessagePrinterTask( "Message$i" ) ) } } } ``` -------------------------------- ### Using classpath*: Prefix for Application Context (Kotlin) Source: https://docs.spring.io/spring-framework/reference/6.2/core/resources.html Demonstrates how to load an application context using the classpath*: prefix in Kotlin, which loads all matching resources from the classpath. ```kotlin val ctx = ClassPathXmlApplicationContext("classpath*:conf/appContext.xml") ``` -------------------------------- ### Example WebLogic SQLException Source: https://docs.spring.io/spring-framework/reference/6.2/data-access/orm/hibernate.html An example of a SQLException that may occur in WebLogic Server when Hibernate is not properly configured with the JTA transaction manager. ```java java.sql.SQLException: The transaction is no longer active - status: 'Committed'. No further JDBC access is allowed within this transaction. ``` -------------------------------- ### Using classpath*: Prefix for Application Context Source: https://docs.spring.io/spring-framework/reference/6.2/core/resources.html Demonstrates how to load an application context using the classpath*: prefix, which loads all matching resources from the classpath. ```java ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:conf/appContext.xml"); ``` -------------------------------- ### Create WebClient with Codec Configuration (Java) Source: https://docs.spring.io/spring-framework/reference/6.2/web/webflux-webclient/client-builder.html Builds a WebClient instance with custom codec configurations. Use when specific codec settings are required. ```java WebClient client = WebClient.builder() .codecs(configurer -> ... ) .build(); ``` -------------------------------- ### Kotlin RouterFunction with GET and Accept Predicate Source: https://docs.spring.io/spring-framework/reference/6.2/web/webflux-functional.html Defines a router function that handles GET requests to '/hello-world' and accepts only 'text/plain' content. ```kotlin val route = coRouter { GET("/hello-world", accept(TEXT_PLAIN)) { ServerResponse.ok().bodyValueAndAwait("Hello World") } } ``` -------------------------------- ### Java RouterFunction with GET and Accept Predicate Source: https://docs.spring.io/spring-framework/reference/6.2/web/webflux-functional.html Defines a router function that handles GET requests to '/hello-world' and accepts only 'text/plain' content. ```java RouterFunction route = RouterFunctions.route() .GET("/hello-world", accept(MediaType.TEXT_PLAIN), request -> ServerResponse.ok().bodyValue("Hello World")).build(); ``` -------------------------------- ### Basic Hello World Controller (Kotlin) Source: https://docs.spring.io/spring-framework/reference/6.2/web/webflux/controller.html A simple Kotlin controller using @RestController and @GetMapping to handle requests to '/hello' and return a String response. ```kotlin @RestController class HelloController { @GetMapping("/hello") fun handle() = "Hello WebFlux" } ``` -------------------------------- ### Perform GET Request with Servlet Request Parameter Source: https://docs.spring.io/spring-framework/reference/6.2/testing/mockmvc/hamcrest/requests.html Add query or form parameters to a GET request using the `param()` method. ```java mockMvc.perform(get("/hotels").param("thing", "somewhere")); ``` -------------------------------- ### Resource Location Example Source: https://docs.spring.io/spring-framework/reference/6.2/core/resources.html Illustrates a typical resource location path within a project structure. ```text com/mycompany/package1/service-context.xml ``` -------------------------------- ### Hibernate JTA Transaction Setup with JtaTransactionManager in LocalSessionFactoryBean Source: https://docs.spring.io/spring-framework/reference/6.2/data-access/transaction/strategies.html An alternative JTA setup where JtaTransactionManager is passed directly into LocalSessionFactoryBean to enforce JTA defaults. ```xml org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml hibernate.dialect=${hibernate.dialect} ``` -------------------------------- ### Java Implementation for Introduction Advice Source: https://docs.spring.io/spring-framework/reference/6.2/core/aop/schema.html The Java method that implements the logic for the introduction advice. It is called when the advised method is executed. ```java public void recordUsage(UsageTracked usageTracked) { usageTracked.incrementUseCount(); } ``` -------------------------------- ### Create and Connect SockJS Client Source: https://docs.spring.io/spring-framework/reference/6.2/web/websocket/fallback.html Demonstrates how to instantiate a SockJS client with WebSocket and XHR transports and connect to a SockJS endpoint. ```java List transports = new ArrayList<>(2); transports.add(new WebSocketTransport(new StandardWebSocketClient())); transports.add(new RestTemplateXhrTransport()); SockJsClient sockJsClient = new SockJsClient(transports); sockJsClient.doHandshake(new MyWebSocketHandler(), "ws://example.com:8080/sockjs"); ``` -------------------------------- ### Perform GET Request with URI Template Query Parameter Source: https://docs.spring.io/spring-framework/reference/6.2/testing/mockmvc/hamcrest/requests.html Specify query parameters directly within the URI template for a GET request. ```java mockMvc.perform(get("/hotels?thing={thing}", "somewhere")); ``` -------------------------------- ### Create WebClient with Codec Configuration (Kotlin) Source: https://docs.spring.io/spring-framework/reference/6.2/web/webflux-webclient/client-builder.html Builds a WebClient instance with custom codec configurations using Kotlin syntax. Use when specific codec settings are required. ```kotlin val webClient = WebClient.builder() .codecs { configurer -> ... } .build() ``` -------------------------------- ### Start RSocket Server with Responder (Kotlin) Source: https://docs.spring.io/spring-framework/reference/6.2/rsocket.html Starts an RSocket server using the Kotlin RSocket API and plugs in the configured RSocketMessageHandler for responders. ```kotlin import org.springframework.beans.factory.getBean val context: ApplicationContext = ... val handler = context.getBean() val server = RSocketServer.create(handler.responder()) .bind(TcpServerTransport.create("localhost", 7000)) .awaitSingle() ```