优秀的编程知识分享平台

网站首页 > 技术文章 正文

《20+种Spring注解大全》:Spring开发者速查手册 涵盖配置 AOP 事务

nanyue 2025-07-28 19:26:55 技术文章 1 ℃

核心提示:掌握Spring注解,开发效率翻倍!本文汇总20+高频注解+实战代码,助你快速定位用法,彻底告别配置混乱时代。


一、配置与Bean管理

  1. @Configuration
    标记当前类为配置类(替代XML)
@Configuration
public class AppConfig {
    @Bean
    public DataSource dataSource() {
        return new HikariDataSource();
    }
}
  1. @Bean
    在配置类中声明Bean(方法返回值即Bean对象)
@Bean(name = "myService") // 自定义Bean名称
public MyService myService() {
    return new MyServiceImpl();
}
  1. @ComponentScan
    自动扫描并注册Bean
@Configuration
@ComponentScan("com.example.service") // 扫描指定包
public class AppConfig {}

二、依赖注入(DI)

  1. @Autowired
    自动装配Bean(按类型优先)
@Service
public class OrderService {
    @Autowired // 注入PaymentService实例
    private PaymentService paymentService;
}
  1. @Qualifier
    解决同类型多个Bean的冲突
@Autowired
@Qualifier("wechatPay") // 指定Bean名称
private PaymentService paymentService;
  1. @Value
    注入配置文件属性
@Value("${app.timeout:5000}") // 默认值5000ms
private int timeout;

三、作用域与生命周期

  1. @Scope
    定义Bean作用域(默认单例)
@Bean
@Scope("prototype") // 每次请求新实例
public Cart cart() {
    return new Cart();
}
  1. @PostConstruct / @PreDestroy
    初始化和销毁回调
@Service
public class CacheService {
    @PostConstruct
    public void initCache() {
        System.out.println("缓存预热...");
    }
    
    @PreDestroy
    public void clearCache() {
        System.out.println("清理缓存...");
    }
}

四、AOP编程

  1. @Aspect + @Component
    声明切面类
@Aspect
@Component
public class LoggingAspect {
    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint jp) {
        System.out.println("调用方法: " + jp.getSignature().getName());
    }
}
  1. 通知类型注解
  • @Before:方法执行前
  • @AfterReturning:方法正常返回后
  • @AfterThrowing:方法抛出异常后
  • @Around:环绕通知(最强大)

五、事务管理

  1. @Transactional
    声明式事务管理(类或方法级)
@Service
public class OrderService {
    @Transactional(
        propagation = Propagation.REQUIRED, 
        rollbackFor = Exception.class
    )
    public void createOrder(Order order) {
        orderDao.save(order);
        inventoryService.deductStock(order); // 事务统一管理
    }
}

六、数据访问

  1. @Repository
    标记数据访问层Bean(DAO)
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
}
  1. @Entity + @Id
    JPA实体映射(Hibernate等ORM框架)
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

七、Web MVC开发

  1. @RestController
    组合注解:
    @Controller + @ResponseBody(直接返回JSON)
@RestController
@RequestMapping("/api/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
}
  1. 请求映射注解
  • @GetMapping → 处理GET请求
  • @PostMapping → 处理POST请求
  • @PutMapping → 处理PUT请求
  • @DeleteMapping → 处理DELETE请求
  1. 参数处理注解
  • @PathVariable:获取URL路径参数
@GetMapping("/users/{id}")
public User getUser(@PathVariable("id") Long userId) { ... }
  1. @RequestParam:获取查询参数
@GetMapping("/search")
public List<User> search(@RequestParam String keyword) { ... }
  1. @RequestBody:解析JSON请求体
@PostMapping("/create")
public User createUser(@RequestBody User user) { ... }

八、条件装配

  1. @Profile
    环境激活配置(dev/test/prod)
@Configuration
@Profile("dev") // 仅在dev环境生效
public class DevDataSourceConfig {
    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder().build();
    }
}
  1. @ConditionalOnProperty
    根据配置属性决定是否创建Bean
@Bean
@ConditionalOnProperty(name = "app.feature.cache", havingValue = "true")
public CacheManager cacheManager() {
    return new RedisCacheManager();
}

九、测试相关

  1. @SpringBootTest
    启动完整Spring上下文进行集成测试
@SpringBootTest
class OrderServiceTest {
    @Autowired
    private OrderService orderService;
}
  1. @MockBean
    在测试中模拟Bean(如模拟数据库)
@SpringBootTest
class PaymentServiceTest {
    @MockBean
    private PaymentGateway paymentGateway; // 模拟支付网关
    
    @Test
    void testPaymentSuccess() {
        when(paymentGateway.process(any())).thenReturn(true);
        // 测试逻辑...
    }
}

高频组合注解(效率加倍!)

注解

等效组合

用途

@SpringBootApplication

@Configuration + @EnableAutoConfiguration + @ComponentScan

Spring Boot启动类

@RestController

@Controller + @ResponseBody

构建REST API

@Service

@Component(语义化特化)

业务逻辑层Bean


使用原则(避坑指南)

  1. 依赖注入首选构造器注入(避免循环依赖)
@Service
public class UserService {
    private final UserRepository repo;
    public UserService(UserRepository repo) { // Spring自动注入
        this.repo = repo;
    }
}
  1. 谨慎使用作用域
  • 无状态服务用singleton(默认)
  • 有状态对象(如购物车)用prototype
  1. 事务注解加在实现类上
    避免AOP代理失效(不推荐加在接口)

统计:Spring官方维护的注解超过150种,但掌握本文这20+核心注解,即可应对90%日常开发场景。建议收藏本文,随用随查!

最近发表
标签列表