当前位置:首页 > 技术 > 正文内容

Spring Boot 核心注解解析

访客 技术 2026年9月1日 1

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.propertiesapplication.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);
    }
}
    

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。