Annotations in Spring Boot

Annotations in Spring Boot

Spring Boot is a popular framework for building production-ready applications quickly. One of its key features is the extensive use of annotations, which simplify configuration and development. Here’s a comprehensive guide to some of the most commonly used annotations in Spring Boot.

Core Annotations

1. @SpringBootApplication

This is a convenience annotation that combines @Configuration, @EnableAutoConfiguration, and @ComponentScan. It marks the main class of a Spring Boot application.


@SpringBootApplication

public class MyApp {

public static void main(String[] args) {

SpringApplication.run(MyApp.class, args);

}

}


2. @Configuration

Indicates that a class declares one or more @Bean methods. These classes are used by Spring's IoC container to manage application components.


@Configuration

public class AppConfig {

@Bean

public MyService myService() {

return new MyServiceImpl();

}

}


3. @ComponentScan

Automatically scans the specified package(s) for Spring components.


@ComponentScan(basePackages = "com.example.myapp")

public class MyAppConfig {

}


4. @EnableAutoConfiguration

Enables Spring Boot’s auto-configuration feature, which attempts to automatically configure your Spring application based on the jar dependencies you have added.


@EnableAutoConfiguration

public class MyApp {

}


Stereotype Annotations

1. @Component

Marks a Java class as a Spring component. It is a generic stereotype for any Spring-managed component.


@Component

public class MyComponent {

}


2. @Service

Specialization of @Component for service-layer components.


@Service

public class MyService {

}


3. @Repository

Specialization of @Component for persistence-layer components. It provides additional benefits such as exception translation.


@Repository

public class MyRepository {

}


4. @Controller

Specialization of @Component for web controllers.


@Controller

public class MyController {

}


5. @RestController

Combines @Controller and @ResponseBody. It is typically used in RESTful web services.


@RestController

public class MyRestController {

}


Dependency Injection Annotations

1. @Autowired

Marks a constructor, field, setter method, or config method to be autowired by Spring's dependency injection facilities.


@Service

public class MyService {

@Autowired

private MyRepository myRepository;

}


2. @Qualifier

Used along with @Autowired to specify which bean should be injected when there are multiple candidates.


@Service

public class MyService {

@Autowired

@Qualifier("mySpecificRepository")

private MyRepository myRepository;

}


3. @Value

Injects values from properties files or system properties.


@Service

public class MyService {

@Value("${my.property}")

private String myProperty;

}


Configuration Annotations

1. @PropertySource

Specifies the location of properties files.


@Configuration

@PropertySource("classpath:application.properties")

public class AppConfig {

}


2. @Profile

Specifies the profiles under which the annotated component or configuration will be active.


@Configuration

@Profile("dev")

public class DevConfig {

}


Web Annotations

1. @RequestMapping

Used to map web requests to specific handler classes or methods.


@RestController

@RequestMapping("/api")

public class MyController {

@RequestMapping("/greeting")

public String greeting() {

return "Hello, World!";

}

}


2. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping

Shortcut annotations for @RequestMapping for specific HTTP methods.


@RestController

@RequestMapping("/api")

public class MyController {

@GetMapping("/greeting")

public String greeting() {

return "Hello, World!";

}

}


3. @PathVariable

Extracts values from the URI path.


@RestController

@RequestMapping("/api")

public class MyController {

@GetMapping("/greeting/{name}")

public String greeting(@PathVariable String name) {

return "Hello, " + name;

}

}


4. @RequestParam

Extracts query parameters from the request.


@RestController

@RequestMapping("/api")

public class MyController {

@GetMapping("/greeting")

public String greeting(@RequestParam String name) {

return "Hello, " + name;

}

}


Data Access Annotations

1. @Entity

Specifies that the class is an entity and is mapped to a database table.


@Entity

public class User {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private Long id;

private String name;

// getters and setters

}


2. @Id

Specifies the primary key of an entity.


@Entity

public class User {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private Long id;

// other fields, getters and setters

}


3. @GeneratedValue

Specifies the generation strategy for the primary key.


@Entity

public class User {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private Long id;

// other fields, getters and setters

}


4. @Table

Specifies the table name in the database.


@Entity

@Table(name = "users")

public class User {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private Long id;

// other fields, getters and setters

}


Transaction Management Annotations

1. @Transactional

Indicates that the annotated method or class should be wrapped in a database transaction.


@Service

@Transactional

public class MyService {

public void performTransactionalOperation() {

// business logic

}

}



1. @SpringBootTest

Indicates that the class is a Spring Boot test. It can be used to load the full application context.


@SpringBootTest

public class MyApplicationTests {

@Test

void contextLoads() {

}

}


2. @MockBean

Creates and injects a mock bean into the Spring application context.


@RunWith(SpringRunner.class)

@SpringBootTest

public class MyServiceTests {

@MockBean

private MyRepository myRepository;

@Autowired

private MyService myService;

@Test

public void testServiceMethod() {

// test logic

}

}


Security Annotations

1. @EnableWebSecurity

Enables Spring Security’s web security support.


@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

// configure security settings

}


2. @Secured

Specifies a list of security roles to be allowed access to a method.


@Service

public class MyService {

@Secured("ROLE_ADMIN")

public void adminOnlyMethod() {

// method logic

}

}


3. @PreAuthorize

Checks the given expression before executing the method.


@Service

public class MyService {

@PreAuthorize("hasRole('ROLE_ADMIN')")

public void adminOnlyMethod() {

// method logic

}

}


Spring Boot’s rich set of annotations simplifies development by reducing boilerplate code and enhancing readability and maintainability. By leveraging these annotations, developers can create robust, production-ready applications with minimal configuration.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了