logo
Spring注解篇 – 想的个人网站
Spring注解篇
本文最后更新于31 天前,其中的信息可能已经过时,如有错误请发送邮件到2327470875@qq.com


📘 Spring Boot 常用注解详细讲解(小白友好版)


1️⃣ 启动类相关

@SpringBootApplication

  • 作用:告诉 Spring Boot:这是项目的入口。
  • 相当于@Configuration + @EnableAutoConfiguration + @ComponentScan
  • 使用场景:项目的 main 方法所在类。
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

2️⃣ 控制层(Controller)

处理请求的接口。

@RestController

  • 作用:定义一个接口类,返回 JSON。
  • 为什么用:如果用 @Controller,默认返回的是页面;而我们大多数时候要返回 JSON。
@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/{id}")
    public String getUser(@PathVariable int id) {
        return "用户ID:" + id;
    }
}

@RequestMapping

  • 作用:定义接口路径。
  • 扩展@GetMapping@PostMapping 等是它的简化版。
@GetMapping("/hello")
public String hello() {
    return "Hello Spring Boot!";
}

@RequestParam

  • 作用:获取 URL 参数。
@GetMapping("/search")
public String search(@RequestParam String keyword) {
    return "搜索关键字:" + keyword;
}

访问:http://localhost:8080/search?keyword=java

@PathVariable

  • 作用:获取路径里的参数。
@GetMapping("/{id}")
public String getUser(@PathVariable int id) {
    return "用户ID:" + id;
}

访问:http://localhost:8080/123 → 返回 用户ID:123

@RequestBody

  • 作用:接收 JSON 请求体。
@PostMapping("/add")
public String addUser(@RequestBody User user) {
    return "接收到用户:" + user.getName();
}

请求体:{"name":"Tom","age":20}


3️⃣ Service 层(业务逻辑)

@Service

  • 作用:标记业务逻辑类,交给 Spring 管理。
@Service
public class UserService {
    public String getUserName() {
        return "小明";
    }
}

4️⃣ DAO 层(数据库操作)

@Mapper

  • 作用:标记这是 MyBatis 的 Mapper 接口,Spring 会自动实现。
@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User getUserById(int id);
}

@Repository

  • 作用:标记 DAO 类,用于数据库异常转换(不常单独写,和 @Mapper 差不多)。

5️⃣ 依赖注入 & 配置

@Autowired

  • 作用:自动注入 Bean(对象)。
@RestController
public class TestController {

    @Autowired
    private UserService userService;

    @GetMapping("/username")
    public String getUserName() {
        return userService.getUserName();
    }
}

@Value

  • 作用:读取配置文件里的值。
@Value("${server.port}")
private int port;

@Configuration + @Bean

  • 作用:定义配置类,注册 Bean。
@Configuration
public class AppConfig {

    @Bean
    public User user() {
        return new User("小红", 18);
    }
}

6️⃣ 事务管理

@Transactional

  • 作用:保证数据库操作要么全成功,要么全失败。
@Service
public class OrderService {

    @Transactional
    public void createOrder() {
        // 扣钱
        // 下单
        // 如果中间出错 → 自动回滚
    }
}

7️⃣ Lombok 注解(简化代码)

@Data

  • 作用:自动生成 getter/setter/toString/equals/hashCode。
@Data
public class User {
    private String name;
    private int age;
}

@Slf4j

  • 作用:自动生成日志对象 log
@Slf4j
@RestController
public class LogController {
    @GetMapping("/log")
    public String testLog() {
        log.info("打印日志");
        return "日志已打印";
    }
}

⚡ 总结

  • 入口类@SpringBootApplication
  • Controller@RestController@GetMapping@RequestBody@PathVariable
  • Service@Service
  • DAO@Mapper@Repository
  • 依赖注入@Autowired@Value@Bean
  • 事务@Transactional
  • 简化代码@Data@Slf4j

要不要我帮你整理成一个 完整的小 Demo 项目(含 Controller + Service + DAO + 配置),你只要复制运行就能看到这些注解如何一起工作?

文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇