AOP相关@Aspect声明一个切面

发布时间:2025-06-24 20:31:03  作者:北方职教升学中心  阅读量:312


@Component@ConfigurationProperties(prefix ="app.database")publicclassDatabaseProperties{// ...}

六、

@AsyncpublicvoidasyncMethod(){// ...}

十七、

// 通常包含在@SpringBootApplication中
  • @ComponentScan

    自动扫描并加载组件。任务调度

    1. @EnableScheduling

      启用任务调度支持。缓存相关

      1. @EnableCaching

        启用缓存支持。

        @Configuration@EnableAsyncpublicclassAsyncConfig{// ...}
      2. @Async

        标记方法为异步执行。数据验证与绑定

        1. @Valid

          开启方法级别验证。

          @ControllerAdvicepublicclassGlobalExceptionHandler{// ...}
        2. @ExceptionHandler

          处理特定异常。

          @ComponentScan(basePackages ="com.example")publicclassAppConfig{}

        三、配置属性

        1. @Value

          注入SpEL表达式结果。

          @EventListenerpublicvoidhandleApplicationEvent(ApplicationEventevent){// ...}

        十九、

    事件监听
    1. @EventListener

      监听并处理应用程序事件。正确使用这些注解可以大大提高开发效率和代码质量。

      @RepositorypublicclassMyRepository{}
    2. @Controller

      控制层组件。

      // 如AOP相关示例所示

    十、

    @RabbitListener(queues ="myQueue")publicvoidreceiveMessage(Stringmessage){// ...}

    十四、

    1. @InitBinder

    用法说明:在Web控制器中自定义数据绑定方法。消息队列

    1. @RabbitListener

      RabbitMQ消息监听器。

      心血制作,太干货,建议收藏!

      一、

      @RunWith(SpringRunner.class)@SpringBootTestpublicclassMyIntegrationTest{// ...}

    2. @MockBean

      在测试环境中替换bean为Mock对象。

      @Configuration@EnableCachingpublicclassCachingConfig{// ...}
    3. @Cacheable

      标记方法结果可缓存。

      @Slf4jpublicclassMyService{publicvoiddoSomething(){log.info("Doing something...");}}

    十六、测试相关

    1. @SpringBootTest

      用于Spring Boot集成测试。依赖注入

      1. @Autowired

        自动注入依赖的bean。缓存(注意:与“缓存相关”重复,这里提供其他缓存注解)

        1. @CachePut

          更新缓存中的数据。Spring Boot核心注解

          1. @SpringBootApplication

            这是Spring Boot项目的核心注解,包含了@SpringBootConfiguration、

            @Configuration@ConditionalOnClass(DataSource.class)publicclassDataSourceConfig{// ...}
            1. @ConditionalOnMissingBean

            用法说明:当Spring容器中不存在指定类型的bean时,才注册bean。国际化与本地化

            1. @MessageSource

            用法说明:与Spring的国际化支持一起使用,定义消息源。AOP相关

            1. @Aspect

              声明一个切面。异常处理

              1. @ControllerAdvice

                全局异常处理。

                publicResponseEntity<?>createUser(@Valid@RequestBodyUseruser){// ...}
              2. @NotNull, @Size, @Pattern

                字段验证注解。异步执行

                1. @EnableAsync

                  启用异步方法执行支持。定义Bean

                  1. @Component

                    泛指组件。

                    @ConfigurationpublicclassAppConfig{// Bean definitions here}
                  2. @EnableAutoConfiguration

                    启用自动配置。

                    @EntitypublicclassUser{// ...}
                    1. @Id

                    用法说明:标注用于标识实体的属性,通常映射到数据库表的主键列。

                    @Configuration@EnableSchedulingpublicclassSchedulingConfig{// ...}
                  3. @Scheduled

                    定义定时任务。

                    @Cacheable("users")publicUsergetUserById(Longid){// ...}

                  十一、条件化配置

                  1. @ConditionalOnClass

                  用法说明:当类路径中存在指定的类时,才注册bean。国际化等。

                  @InitBinderpublicvoidinitBinder(WebDataBinderbinder){// 自定义数据绑定逻辑}

                  二十三、数据访问、

                  @ConfigurationpublicclassMessageSourceConfig{@BeanpublicMessageSourcemessageSource(){ResourceBundleMessageSourcemessageSource =newResourceBundleMessageSource();messageSource.setBasename("messages");// 假设资源文件名为messages.propertiesreturnmessageSource;}}

                  这些注解覆盖了Spring Boot开发的多个方面,从核心功能到Web服务、Spring MVC相关

                  1. @ModelAttribute

                  用法说明:绑定请求参数到模型属性,或者暴露一个方法参数为模型属性。安全性

                  1. @EnableWebSecurity

                    启用Spring Security的Web安全性。Web相关扩展

                    1. @ControllerAdvice(已在异常处理中给出示例)

                    用法说明(扩展):除了异常处理,还可以用于全局数据绑定、@EnableAutoConfiguration和@ComponentScan。事务管理

                    1. @Transactional

                      声明式事务管理。

                      @EnableWebSecuritypublicclassWebSecurityConfigextendsWebSecurityConfigurerAdapter{// ...}
                    2. @PreAuthorize, @Secured

                      方法级别的安全性注解。Spring Data JPA相关

                      1. @Entity

                      用法说明:标记一个类为实体类,映射到数据库中的一个表。

                      @Controller@SessionAttributes("attributeName")publicclassMyController{// ...}

                      二十四、请求预处理等。

                      @ControllerpublicclassMyController{}

                    3. @RestController

                      控制层组件,返回数据直接写入HTTP响应体。

                      如果你渴望深入了解这50个注解的完整内容,想要获取更全面的知识和指导,那么请立即行动!关注我们,了解更多java和web前端学习干货。

                      // 如上RESTful Web服务示例所示

                    八、

                    @ServicepublicclassMyService{}

                  2. @Repository

                    数据访问组件。

                  十五、响应时间等。

                  // 如上例所示

                2. @RequestBody

                  绑定请求体到方法参数。

                  @PreAuthorize("hasRole('ROLE_USER')")publicvoidsecureMethod(){// ...}

                二十、安全性、

                @ComponentpublicclassMyComponent{@Value("${app.name}")privateStringappName;}

              3. @ConfigurationProperties

                绑定外部配置到Java对象。

                @CachePut(value ="users",key ="#user.id")publicUserupdateUser(Useruser){// ...}
              4. @CacheEvict

                清除缓存条目(已在“缓存相关”中给出示例)。配置与自动配置

                1. @Configuration

                  声明当前类是一个配置类。

                  @Bean@ConditionalOnMissingBeanpublicMyBeanmyBean(){returnnewMyBean();}
                  1. @ConditionalOnProperty

                  用法说明:根据配置文件中的属性值来条件化地注册bean。

                  @ModelAttributepublicvoidpopulateModel(@RequestParamStringattributeName,Modelmodel){model.addAttribute(attributeName,"attributeValue");}
                  1. @SessionAttributes

                  用法说明:将模型属性存储到HTTP session中。

                  @ServicepublicclassMyService{@AutowiredprivateMyRepositoryrepository;}

                五、

                // 通常通过添加spring-boot-starter-actuator依赖并配置相关属性来启用

                二十五、

                @ComponentpublicclassMyComponent{}

              5. @Service

                业务层组件。

                publicclassUser{@NotNullprivateLongid;// ... other validations}

              九、

              @RepositoryRestResource(collectionResourceRel ="users",path ="users")publicinterfaceUserRepositoryextendsJpaRepository<User,Long>{// ...}

              二十二、

              @SpringBootTestpublicclassMyServiceTest{@MockBeanprivateMyRepositoryrepository;// ...}

            七、RESTful Web服务

            1. @GetMapping, @PostMapping, etc.

              定义HTTP方法映射。

              @Aspect@ComponentpublicclassLoggingAspect{// ...}
            2. @Before, @After, etc.

              定义通知类型。

              @EntitypublicclassUser{@IdprivateLongid;// ...}
              1. @RepositoryRestResource

              用法说明:与Spring Data REST一起使用,为JPA仓库暴露RESTful API。日志记录

              1. @Slf4j(Lombok提供)

                自动生成SLF4J的Logger实例。

                @RestControllerpublicclassMyRestController{// ...}

              四、

              @Configuration@ConditionalOnProperty(name ="feature.enabled",havingValue ="true")publicclassFeatureConfig{// ...}

              二十一、性能监控与指标

              1. @EnableWebMvcMetrics(Spring Boot Actuator提供)

              用法说明:启用Web MVC的度量收集,如HTTP请求计数器、

              @ExceptionHandler(Exception.class)publicResponseEntity<Object>handleException(Exceptione){// ...}

            十八、

            @SpringBootApplicationpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}

          二、

          @ServicepublicclassUserService{@TransactionalpublicvoidcreateUser(Useruser){// ...}}

        十二、

        @Scheduled(fixedRate =5000)publicvoiddoSomething(){// ...}

      十三、

      @RestControllerpublicclassUserController{@GetMapping("/users/{id}")publicUsergetUser(@PathVariableLongid){// ...}}

    2. @PathVariable

      从URL路径中提取变量值。