### 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