### Kotlin Test Fixture Setup Source: https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/fixture-di.html Example of setting up a test fixture with a dependency on TitleRepository in Kotlin. ```kotlin fun setTitleRepository(titleRepository: HibernateTitleRepository) { this.titleRepository = titleRepository } @Test fun findById() { val title = titleRepository.findById(10) assertNotNull(title) } } ``` -------------------------------- ### Programmatic Transaction Management Example Source: https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/tx.html Demonstrates starting, flagging for commit, ending, and re-starting test-managed transactions programmatically. Changes flagged for commit will be committed, while subsequent actions after re-starting are 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")); } } ``` -------------------------------- ### Argument Type Matching Examples Source: https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-method-injection.html Examples demonstrating how to specify argument types for method replacement in XML. Shows different ways to match `java.lang.String`. ```xml java.lang.String String Str ``` -------------------------------- ### Programmatic Transaction Management Example (Kotlin) Source: https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/tx.html Demonstrates starting, flagging for commit, ending, and re-starting test-managed transactions programmatically in Kotlin. Changes flagged for commit will be committed, while subsequent actions after re-starting are 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")) } } ``` -------------------------------- ### Example Bean with init Method (Kotlin) Source: https://docs.spring.io/spring-framework/reference/core/beans/factory-nature.html A Kotlin class demonstrating an `init` method for bean initialization. This is the Kotlin equivalent of the Java example, used with `init-method` configuration. ```kotlin class ExampleBean { fun init() { // do some initialization work } } ``` -------------------------------- ### Client SEND Command Example Source: https://docs.spring.io/spring-framework/reference/web/websocket/stomp/overview.html Demonstrates a client sending a trade request to the server. This example includes destination, content type, and content length headers, along with a JSON payload. ```text SEND destination:/queue/trade content-type:application/json content-length:44 {"action":"BUY","ticker":"MMM","shares":44}^@ ``` -------------------------------- ### Basic MockRestServiceServer Setup (Kotlin) Source: https://docs.spring.io/spring-framework/reference/testing/spring-mvc-test-client.html Demonstrates the basic setup of MockRestServiceServer to mock a RestTemplate in Kotlin. Use this for simple client-side testing where you need to stub specific requests and responses. ```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() ``` -------------------------------- ### Initialize Database with Scripts Source: https://docs.spring.io/spring-framework/reference/data-access/jdbc/initializing-datasource.html Use this snippet to run SQL scripts for creating a database schema and populating it with test data. Script locations can be Ant-style patterns. ```xml ``` -------------------------------- ### MVC Controller Example (Java) Source: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-uri-building.html A sample Spring MVC controller with a GET mapping for retrieving bookings. ```java @Controller @RequestMapping("/hotels/{hotel}") public class BookingController { @GetMapping("/bookings/{booking}") public ModelAndView getBooking(@PathVariable Long booking) { // ... } } ``` -------------------------------- ### Basic Hello World Controller (Kotlin) Source: https://docs.spring.io/spring-framework/reference/web/webflux/controller.html A simple Kotlin controller demonstrating a GET mapping for a '/hello' endpoint that returns a String. ```kotlin @RestController class HelloController { @GetMapping("/hello") fun handle() = "Hello WebFlux" } ``` -------------------------------- ### Kotlin Controller Example Source: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-uri-building.html A sample Kotlin controller with request mappings. ```kotlin @RequestMapping("/people/{id}/addresses") class PersonAddressController { @RequestMapping("/{country}") fun getAddress(@PathVariable country: String): HttpEntity { ... } } ``` -------------------------------- ### MVC Controller Example (Kotlin) Source: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-uri-building.html A sample Spring MVC controller with a GET mapping for retrieving bookings, written in Kotlin. ```kotlin @Controller @RequestMapping("/hotels/{hotel}") class BookingController { @GetMapping("/bookings/{booking}") fun getBooking(@PathVariable booking: Long): ModelAndView { // ... } } ``` -------------------------------- ### Basic Context Hierarchy Configuration Source: https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/ctx-management/hierarchies.html Demonstrates a simple context hierarchy setup using @ContextHierarchy with distinct configuration files for different levels. ```java @ExtendWith(SpringExtension.class) @ContextHierarchy({ @ContextConfiguration(name = "parent", locations = "/app-config.xml"), @ContextConfiguration(name = "child", locations = "/user-config.xml") }) class BaseTests {} @ContextHierarchy( @ContextConfiguration(name = "child", locations = "/order-config.xml") ) class ExtendedTests extends BaseTests {} ``` -------------------------------- ### Kotlin Annotated Controller Example Source: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller.html A basic Spring MVC controller written in Kotlin using annotations to handle GET requests and add attributes to the model. ```kotlin import org.springframework.ui.set @Controller class HelloController { @GetMapping("/hello") fun handle(model: Model): String { model["message"] = "Hello World!" return "index" } } ``` -------------------------------- ### Basic Hello World Controller (Java) Source: https://docs.spring.io/spring-framework/reference/web/webflux/controller.html A simple Java controller demonstrating a GET mapping for a '/hello' endpoint that returns a String. ```java @RestController public class HelloController { @GetMapping("/hello") public String handle() { return "Hello WebFlux"; } } ``` -------------------------------- ### Java Annotated Controller Example Source: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller.html A basic Spring MVC controller written in Java using annotations to handle GET requests and add attributes to the model. ```java @Controller public class HelloController { @GetMapping("/hello") public String handle(Model model) { model.addAttribute("message", "Hello World!"); return "index"; } } ``` -------------------------------- ### Resource Path Example Source: https://docs.spring.io/spring-framework/reference/core/resources.html Illustrates a typical resource path for a Spring context file. ```text com/mycompany/package1/service-context.xml ``` -------------------------------- ### Java @ResponseBody Method Source: https://docs.spring.io/spring-framework/reference/web/webflux/controller/ann-methods/responsebody.html Use @ResponseBody on a method to serialize its return value to the HTTP response body using an HttpMessageWriter. This example demonstrates its usage with a GET mapping. ```java @GetMapping("/accounts/{id}") @ResponseBody public Account handle() { // ... } ``` -------------------------------- ### Pure XML Declarative Approach for Transactional and Profiling Aspects Source: https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/applying-more-than-just-tx-advice.html Demonstrates the same setup as the previous example but uses a purely XML declarative approach for configuring beans and aspects. ```xml ``` -------------------------------- ### Configuring and Using REST Client with Custom Resolver (Java) Source: https://docs.spring.io/spring-framework/reference/integration/rest-clients.html Demonstrates building a RestClient, creating an adapter, configuring HttpServiceProxyFactory with a custom argument resolver, and invoking a service method. ```java RestClient restClient = RestClient.builder().baseUrl("https://api.github.com/").build(); RestClientAdapter adapter = RestClientAdapter.create(restClient); HttpServiceProxyFactory factory = HttpServiceProxyFactory .builderFor(adapter) .customArgumentResolver(new SearchQueryArgumentResolver()) .build(); RepositoryService repositoryService = factory.createClient(RepositoryService.class); Search search = Search.create() .owner("spring-projects") .language("java") .query("rest") .build(); List repositories = repositoryService.searchRepository(search); ``` -------------------------------- ### Java Controller Example Source: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-uri-building.html A sample Java controller with request mappings. ```java @RequestMapping("/people/{id}/addresses") public class PersonAddressController { @RequestMapping("/{country}") public HttpEntity getAddress(@PathVariable String country) { ... } } ``` -------------------------------- ### Kotlin @ResponseBody Method Source: https://docs.spring.io/spring-framework/reference/web/webflux/controller/ann-methods/responsebody.html Use @ResponseBody on a method to serialize its return value to the HTTP response body using an HttpMessageWriter. This example demonstrates its usage with a GET mapping in Kotlin. ```kotlin @GetMapping("/accounts/{id}") @ResponseBody fun handle(): Account { // ... } ``` -------------------------------- ### ExampleJob Implementation Source: https://docs.spring.io/spring-framework/reference/integration/scheduling.html Implement ExampleJob extending QuartzJobBean to receive job data properties like 'timeout' automatically. ```java package example; public class ExampleJob extends QuartzJobBean { private int timeout; /** * Setter called after the ExampleJob is instantiated * with the value from the JobDetailFactoryBean. */ public void setTimeout(int timeout) { this.timeout = timeout; } protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException { // do the actual work } } ``` -------------------------------- ### Kotlin @BeforeTransaction Example Source: https://docs.spring.io/spring-framework/reference/testing/annotations/integration-spring/annotation-beforetransaction.html This Kotlin snippet demonstrates how to use the @BeforeTransaction annotation to run logic prior to a transaction starting in a test context. The annotated function should return Unit (void). ```kotlin @BeforeTransaction fun beforeTransaction() { // logic to be run before a transaction is started } ``` -------------------------------- ### Get Resource with a path that appears absolute Source: https://docs.spring.io/spring-framework/reference/core/resources.html FileSystemResource treats paths as relative to the current working directory when not attached to a FileSystemXmlApplicationContext. When attached, all paths are treated as relative, even those starting with a slash. ```java FileSystemXmlApplicationContext ctx = ...; ctx.getResource("/some/resource/path/myTemplate.txt"); ``` ```kotlin val ctx: FileSystemXmlApplicationContext = ... ctx.getResource("/some/resource/path/myTemplate.txt") ``` -------------------------------- ### JDBC Properties File Example Source: https://docs.spring.io/spring-framework/reference/core/beans/java/composing-configuration-classes.html Provides sample database connection properties. ```properties jdbc.url=jdbc:hsqldb:hsql://localhost/xdb jdbc.username=sa jdbc.password= ``` -------------------------------- ### WebDriver Setup with Pre-configured MockMvc Instance Source: https://docs.spring.io/spring-framework/reference/testing/mockmvc/htmlunit/webdriver.html Sets up WebDriver by first configuring a MockMvc instance separately and then supplying it to MockMvcHtmlUnitDriverBuilder. This provides full access to MockMvc's capabilities. ```java 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(); ``` -------------------------------- ### Annotation Use-Site Targets for Bean Validation Source: https://docs.spring.io/spring-framework/reference/languages/kotlin/annotations.html Provides an example of using annotation use-site targets like @field:NotNull or @get:Size for bean validation on properties or constructor parameters in Kotlin. ```kotlin @field:NotNull @get:Size(min=5, max=15) ``` -------------------------------- ### Basic @Configuration Class with @Bean Method (Kotlin) Source: https://docs.spring.io/spring-framework/reference/core/beans/java/basic-concepts.html Demonstrates the equivalent of the Java example using Kotlin, showcasing @Configuration and @Bean annotations for bean definition. ```kotlin @Configuration class AppConfig { @Bean fun myService(): MyServiceImpl { return MyServiceImpl() } } ``` -------------------------------- ### Web Application Context MockMvc Setup (Kotlin) Source: https://docs.spring.io/spring-framework/reference/testing/mockmvc/hamcrest/setup.html This Kotlin snippet shows how to set up MockMvc using a WebApplicationContext, typically defined via an XML configuration. ```kotlin @SpringJUnitWebConfig(locations = ["my-servlet-context.xml"]) class MyWebTests { lateinit var mockMvc: MockMvc @BeforeEach fun setup(wac: WebApplicationContext) { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build() } // ... } ``` -------------------------------- ### Read BLOB and CLOB data using JdbcTemplate (Java) Source: https://docs.spring.io/spring-framework/reference/data-access/jdbc/parameter-handling.html Reads BLOB and CLOB data from a database table using JdbcTemplate and a RowMapper. This snippet is a partial example showing the setup for reading data. ```java List> l = jdbcTemplate.query("select id, a_clob, a_blob from lob_table", new RowMapper>() { public Map mapRow(ResultSet rs, int i) throws SQLException { Map results = new HashMap(); ``` -------------------------------- ### Basic After Throwing Advice (Java) Source: https://docs.spring.io/spring-framework/reference/core/aop/ataspectj/advice.html Use @AfterThrowing to declare advice that runs 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() { // ... } } ``` -------------------------------- ### Configuring and Using REST Client with Custom Resolver (Kotlin) Source: https://docs.spring.io/spring-framework/reference/integration/rest-clients.html Demonstrates building a RestClient, creating an adapter, configuring HttpServiceProxyFactory with a custom argument resolver, and invoking a service method in Kotlin. ```kotlin val restClient = RestClient.builder().baseUrl("https://api.github.com/").build() val adapter = RestClientAdapter.create(restClient) val factory = HttpServiceProxyFactory .builderFor(adapter) .customArgumentResolver(SearchQueryArgumentResolver()) .build() val repositoryService = factory.createClient(RepositoryService::class.java) val search = Search(owner = "spring-projects", language = "java", query = "rest") val repositories = repositoryService.searchRepository(search) ``` -------------------------------- ### Java Proceed Call with Arguments Source: https://docs.spring.io/spring-framework/reference/core/aop/ataspectj/advice.html Demonstrates how to bind method parameters in order for a proceed call with arguments in Java. Ensure the advice signature binds each method parameter. ```java @Around("execution(List find*(..)) && " + "com.xyz.CommonPointcuts.inDataAccessLayer() && " + "args(accountHolderNamePattern)") __**(1)** public Object preProcessQueryPattern(ProceedingJoinPoint pjp, String accountHolderNamePattern) throws Throwable { String newPattern = preProcess(accountHolderNamePattern); return pjp.proceed(new Object[] {newPattern}); } ``` -------------------------------- ### Configure WebClient with MockMvcConfigurer and Hosts (Kotlin) Source: https://docs.spring.io/spring-framework/reference/testing/mockmvc/htmlunit/mah.html Builds a WebClient in Kotlin with additional configuration, including applying a MockMvcConfigurer, setting a contextPath, and specifying hosts for MockMvc usage. ```kotlin lateinit var webClient: WebClient @BeforeEach fun setup() { webClient = MockMvcWebClientBuilder // demonstrates applying a MockMvcConfigurer (Spring Security) .webAppContextSetup(context, springSecurity()) // 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() } ``` -------------------------------- ### Simplified Test Methods using Custom Annotation (Kotlin) Source: https://docs.spring.io/spring-framework/reference/testing/annotations/integration-meta.html Kotlin example showing the use of the custom @TransactionalIntegrationTest meta-annotation for simplifying test method configurations. It applies the composed annotation to methods requiring transactional integration test setup. ```kotlin @TransactionalIntegrationTest fun saveOrder() { } @TransactionalIntegrationTest fun deleteOrder() { } ``` -------------------------------- ### AspectJ Profiling Output Example Source: https://docs.spring.io/spring-framework/reference/core/aop/using-aspectj.html This is an example of the output generated by the ProfilingAspect when it captures execution time. ```text Calculating entitlement StopWatch 'ProfilingAspect': running time (millis) = 1234 ------ ----- ---------------------------- ms % Task name ------ ----- ---------------------------- 01234 100% calculateEntitlement ``` -------------------------------- ### Create and Connect SockJS Client Source: https://docs.spring.io/spring-framework/reference/web/websocket/fallback.html Demonstrates how to instantiate a `SockJsClient` with WebSocket and XHR transports and initiate a handshake with a SockJS endpoint. ```java List transports = new ArrayList<>(2); transports.add(new WebSocketTransport(new StandardWebSocketClient())); transports.add(new RestClientXhrTransport()); SockJsClient sockJsClient = new SockJsClient(transports); sockJsClient.doHandshake(new MyWebSocketHandler(), "ws://example.com:8080/sockjs"); ``` -------------------------------- ### Complex Elvis Operator Example (Kotlin) Source: https://docs.spring.io/spring-framework/reference/core/expressions/language-ref/operator-elvis.html Provides the Kotlin equivalent for the complex SpEL Elvis operator example. ```kotlin val parser = SpelExpressionParser() val context = SimpleEvaluationContext.forReadOnlyDataBinding().build() val tesla = Inventor("Nikola Tesla", "Serbian") var name = parser.parseExpression("name ?: 'Elvis Presley'").getValue(context, tesla, String::class.java) println(name) // Nikola Tesla tesla.setName("") name = parser.parseExpression("name ?: 'Elvis Presley'").getValue(context, tesla, String::class.java) println(name) // Elvis Presley ``` -------------------------------- ### Basic Context Hierarchy Configuration (Kotlin) Source: https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/ctx-management/hierarchies.html Kotlin version of a basic context hierarchy setup, illustrating the use of @ContextHierarchy with distinct configuration files. ```kotlin @ExtendWith(SpringExtension::class) @ContextHierarchy( ContextConfiguration(name = "parent", locations = ["/app-config.xml"]), ContextConfiguration(name = "child", locations = ["/user-config.xml"])) open class BaseTests {} @ContextHierarchy( ContextConfiguration(name = "child", locations = ["/order-config.xml"]) ) class ExtendedTests : BaseTests() {} ``` -------------------------------- ### Example Property Override Configuration Source: https://docs.spring.io/spring-framework/reference/core/beans/factory-extension.html An example of a properties file used to override 'driverClassName' and 'url' properties for a 'dataSource' bean. ```properties dataSource.driverClassName=com.mysql.jdbc.Driver dataSource.url=jdbc:mysql:mydb ``` -------------------------------- ### Example Exception from WebLogic Source: https://docs.spring.io/spring-framework/reference/data-access/orm/hibernate.html This is 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. ``` -------------------------------- ### Get Direct Access to MvcResult Source: https://docs.spring.io/spring-framework/reference/testing/mockmvc/hamcrest/expectations.html Append `.andReturn()` after expectations to get direct access to the `MvcResult` object for further inspection or custom assertions. ```java MvcResult mvcResult = mockMvc.perform(post("/persons")).andExpect(status().isOk()).andReturn(); // ... ```