Spring Boot 核心注解解析
1. @SpringBootApplication
这是Spring Boot应用程序的入口点,它是一个复合注解,包含了@Configuration、@EnableAutoConfiguration和@ComponentScan。它的存在意味着Spring Boot会扫描当前包及其子包下的所有组件,并自动配置应用程序上下文。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ApplicationLauncher {
public static void main(String[] args) {
SpringApplication.run(ApplicationLauncher.class, args);
}
}
2. @RestController
此注解用于声明一个RESTful控制器。它相当于在类级别同时使用了@Controller和@ResponseBody,意味着该类的所有方法返回值都将直接写入HTTP响应体,而非被解析为视图名称。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1")
public class GreetingController {
@GetMapping("/greet")
public String greetUser() {
return "Hello from the API!";
}
}
3. @RequestMapping
@RequestMapping注解用于将Web请求映射到具体的处理方法上。它可以作用于类级别(定义基础路径)和方法级别(定义具体端点)。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Arrays;
@RestController
@RequestMapping("/data")
public class DataController {
@GetMapping("/items")
public List<String> fetchItems() {
return Arrays.asList("Item A", "Item B", "Item C");
}
@GetMapping("/users/{userId}")
public String fetchUserById(@PathVariable Long userId) {
return "Details for User ID: " + userId;
}
}
4. @Autowired
@Autowired注解用于实现依赖注入(Dependency Injection)。Spring容器会根据类型自动查找并注入所需的Bean实例。它可以应用于构造函数、字段或Setter方法。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderProcessingService {
private final InventoryRepository inventoryRepo;
// 构造函数注入
@Autowired
public OrderProcessingService(InventoryRepository inventoryRepo) {
this.inventoryRepo = inventoryRepo;
}
public void processOrder(Long orderId) {
// 使用 inventoryRepo 进行数据库操作
System.out.println("Processing order: " + orderId);
}
}
5. @Service
@Service注解标记一个类为服务层组件。Spring会将带有此注解的类识别为Bean,并纳入其管理范围,常用于封装业务逻辑。
import org.springframework.stereotype.Service;
@Service("customerService") // 可选的Bean名称
public class CustomerService {
public String getCustomerName(Long customerId) {
// 模拟从数据库查询
return "Customer" + customerId;
}
}
6. @Repository
@Repository注解用于标记数据访问层(DAO)组件。它指示Spring将该类视为数据存储的封装。Spring会进行异常转换,将特定于数据存储技术的异常(如SQLException)转换为Spring的通用数据访问异常体系。
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
// 假设有一个实体类 Product
@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
// Spring Data JPA 会自动实现基本的CRUD操作
// 也可以在这里定义自定义的查询方法
List<Product> findByNameContaining(String keyword);
}
7. @Configuration
@Configuration注解用于指示一个类为Bean的配置源。带有此注解的类可以包含@Bean注解的方法,这些方法定义的Bean将由Spring IoC容器管理。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfiguration {
@Bean
public EmailSender emailSender() {
EmailSender sender = new EmailSender();
sender.setHost("smtp.example.com");
return sender;
}
}
8. @EnableAutoConfiguration
@EnableAutoConfiguration注解是Spring Boot自动配置的核心。它会根据类路径中的依赖项,自动配置Spring应用程序的各个方面。通常情况下,它被包含在@SpringBootApplication注解中,所以不需要显式地在主应用程序类上使用。
// 通常不直接使用,而是通过 @SpringBootApplication 间接启用
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// 示例:如果需要单独启用自动配置
@EnableAutoConfiguration
public class StandaloneAutoConfigApp {
public static void main(String[] args) {
SpringApplication.run(StandaloneAutoConfigApp.class, args);
}
}
9. @Component
@Component是最通用的Spring Bean的注解。任何Spring管理的类都可以使用此注解。@Service, @Repository, @Controller都是@Component的特化形式。
import org.springframework.stereotype.Component;
@Component("utilityBean") // 可选的Bean ID
public class SystemUtility {
public void logMessage(String message) {
System.out.println("LOG: " + message);
}
}
10. @Value
@Value注解用于将外部化配置(如application.properties或application.yml中的属性)注入到Bean的字段或构造函数参数中。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AppSettings {
@Value("${database.url}")
private String dbUrl;
@Value("${app.version:1.0.0}") // 提供默认值
private String appVersion;
public void displaySettings() {
System.out.println("Database URL: " + dbUrl);
System.out.println("App Version: " + appVersion);
}
}