Spring Boot 备忘清单 & springboot cheatsheet & 速查表

依赖注入(Dependency Injection)

依赖注入是Spring框架的核心概念之一,它通过控制反转(IoC,Inversion of Control)的方式管理对象之间的依赖关系,从而实现松耦合、可测试和可维护的代码结构。Spring Boot通过自动配置的方式支持依赖注入,以下是一些关键点:

自动装配(Auto-configuration)

Spring Boot根据类路径中的依赖项自动配置应用程序上下文。这包括自动扫描和注册带有特定注解(如@Component@Service@Repository等)的Bean,以及自动解析和注入这些Bean之间的依赖关系。

Bean的声明和管理

开发者可以使用@Autowired注解在需要依赖注入的地方注入其他Bean,Spring Boot会自动解析和注入所需的依赖。例如:

@RestController
public class MyContr {
  private final MyService myService;
  
  @Autowired
  public MyContr(MyService myService) {
      this.myService = myService;
  }
  
  // Controller methods
}

在上面的例子中,MyController中的MyService依赖通过构造函数注入。

条件化注入

Spring Boot支持根据条件选择性地注入Bean。例如,可以使用 @Conditional 注解或 @ConditionalOnProperty 注解根据特定的条件决定是否创建和注入Bean。

面向切面编程(Aspect-Oriented Programming)

面向切面编程是一种软件开发方法,用于分离横切关注点(cross-cutting concerns),例如日志、事务管理、安全性等,以便更好地模块化和管理应用程序。Spring Boot通过整合Spring AOP框架支持面向切面编程,以下是相关的说明:

切面(Aspect)

切面是一个模块化的类,它包含了横切关注点的逻辑。在Spring Boot中,可以使用@Aspect注解标记一个类作为切面,并通过@Before@After@Around等注解定义切面的具体行为。

切点(Pointcut)

切点定义了在应用程序中哪些位置应用切面逻辑。切点表达式使用execution关键字指定要拦截的方法调用。例如:

@Aspect
@Component
public class LoggingAspect {
    
    @Before("execution(* com.example.service.*.*(..))")
    public void beforeServiceMethods(JoinPoint joinPoint) {
        // Advice logic before service method execution
    }
    
    // Other advices (e.g., @After, @Around) can be defined similarly
}

通知(Advice)

通知是在切点处执行的具体逻辑,包括@Before@AfterReturning@AfterThrowing@Around等。例如,在上面的例子中,beforeServiceMethods方法就是一个@Before通知,它在目标方法执行之前执行。

配置和启用

Spring Boot通过自动配置和注解扫描使得使用AOP变得非常简单。通常情况下,只需在切面类上加上@Aspect注解,并确保它被Spring Boot的组件扫描机制扫描到即可。