Spring & Testing Annotations - Definitions and Examples
Core Spring Boot
@SpringBootApplication
Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. It serves as the entry point
of a Spring Boot application.
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@Component
Used to mark a Java class as a component so that Spring can detect it during component scanning.
@Component
public class MyComponent {
public void doWork() {
System.out.println("Working...");
}
}
@Autowired
Marks a constructor, field, or setter method to be autowired by Spring's dependency injection.
@Autowired
private MyComponent myComponent;
@Bean
Used on methods to define Spring-managed beans within a @Configuration class.
@Bean
public MyService myService() {
return new MyServiceImpl();
}
@Configuration
Indicates that the class contains @Bean definitions for the Spring context.
@Configuration
public class AppConfig {
@Bean
Spring & Testing Annotations - Definitions and Examples
public MyService myService() {
return new MyService();
}
}
Web Annotations (Spring MVC)
@RestController
A convenience annotation that combines @Controller and @ResponseBody. It is used to build RESTful web
services.
@RestController
public class MyRestController {
@GetMapping("/hello")
public String sayHello() {
return "Hello World";
}
}
@RequestMapping
Maps HTTP requests to handler methods of MVC and REST controllers.
@RequestMapping("/users")
public class UserController { }
@GetMapping
Shortcut for @RequestMapping(method = RequestMethod.GET).
@GetMapping("/users")
public List<User> getAllUsers() { return userService.findAll(); }
@PostMapping
Shortcut for @RequestMapping(method = RequestMethod.POST).
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@PutMapping
Shortcut for @RequestMapping(method = RequestMethod.PUT).
@PutMapping("/users/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
Spring & Testing Annotations - Definitions and Examples
return userService.update(id, user);
}
@DeleteMapping
Shortcut for @RequestMapping(method = RequestMethod.DELETE).
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
@RequestBody
Indicates a method parameter should be bound to the body of the HTTP request.
@PostMapping("/add")
public ResponseEntity<User> addUser(@RequestBody User user) {
return ResponseEntity.ok(userService.save(user));
}
@PathVariable
Binds a method parameter to a URI template variable.
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
Spring Data (MongoDB/JPA)
@Document
Marks a class as a domain object that will be persisted to MongoDB.
@Document(collection = "users")
public class User {
@Id
private String id;
}
@Id
Defines the primary key field for MongoDB or JPA entities.
@Id
private String id;
Spring & Testing Annotations - Definitions and Examples
@Indexed
Indicates that the field should be indexed in the MongoDB collection.
@Indexed(unique = true)
private String email;
@DBRef
Used to declare references between documents in MongoDB.
@DBRef
private List<Role> roles;
@Transactional
Specifies that a method or class should be executed within a transaction.
@Transactional
public void updateData() {
repository.save(data);
}
@EnableTransactionManagement
Enables Spring's annotation-driven transaction management capability.
@Configuration
@EnableTransactionManagement
public class TransactionConfig { }
Lombok
@Data
Generates getters, setters, equals, hashCode, and toString methods.
@Data
public class User {
private String name;
private int age;
}
@Builder
Generates a builder pattern for the class.
@Builder
public class User {
private String name;
Spring & Testing Annotations - Definitions and Examples
private int age;
}
@NonNull
Generates null-checks for annotated fields or parameters.
public User(@NonNull String name) {
this.name = name;
}
@NoArgsConstructor
Generates a no-argument constructor.
@NoArgsConstructor
public class User { }
@Slf4j
Adds a static SLF4J logger to the class.
@Slf4j
public class MyClass {
public void logSomething() {
log.info("Logging with Lombok!");
}
}
JUnit & Testing
@SpringBootTest
Used to test Spring Boot applications with a full context.
@SpringBootTest
public class MyAppTests { }
@Test
Marks a method as a test case in JUnit 5.
@Test
void testSum() {
assertEquals(4, 2 + 2);
}
@ParameterizedTest
Spring & Testing Annotations - Definitions and Examples
Allows a test method to be executed multiple times with different arguments.
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testWithMultipleValues(int value) {
assertTrue(value > 0);
}
@Disabled
Disables a test method or class.
@Disabled
@Test
void skippedTest() { }
@CsvSource
Provides CSV data for @ParameterizedTest.
@ParameterizedTest
@CsvSource({"1,one", "2,two"})
void testCsv(int number, String word) {
assertNotNull(word);
}
@ValueSource
Provides a simple source of literal values for @ParameterizedTest.
@ParameterizedTest
@ValueSource(strings = {"Hello", "JUnit"})
void testStrings(String input) {
assertNotNull(input);
}
@EnumSource
Supplies enum constants for @ParameterizedTest.
@ParameterizedTest
@EnumSource(TimeUnit.class)
void testEnum(TimeUnit unit) {
assertNotNull(unit);
}
@BeforeEach
Executed before each test method.
Spring & Testing Annotations - Definitions and Examples
@BeforeEach
void setup() {
// initialize before each test
}
@AfterEach
Executed after each test method.
@AfterEach
void teardown() {
// clean up
}
@BeforeAll
Executed once before all test methods.
@BeforeAll
static void init() {
// setup before all tests
}
@AfterAll
Executed once after all test methods.
@AfterAll
static void cleanup() {
// cleanup after all tests
}
@Mock
Creates a mock instance of a class using Mockito.
@Mock
private UserService userService;