Quick Guide to the Spring @Enable Annotations – 关于Spring @Enable注解的快速指南

最后修改: 2017年 8月 10日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Spring comes with a set of @Enable annotations that make it easier for developers to configure a Spring application. These annotations are used in conjunction with the @Configuration annotation.

Spring带有一组@Enable注解,使开发者更容易配置Spring应用程序。这些注解是@Configuration注解一起使用的

In this article we will be looking at some these annotations:

在这篇文章中,我们将看一些这些注释。

  • @EnableWebMvc
  • @EnableCaching
  • @EnableScheduling
  • @EnableAsync
  • @EnableWebSocket
  • @EnableJpaRepositories
  • @EnableTransactionManagement
  • @EnableJpaAuditing

2. @EnableWebMvc

2.@EnableWebMvc

The @EnableWebMvc annotation is used for enabling Spring MVC in an application and works by importing the Spring MVC Configuration from WebMvcConfigurationSupport.

@EnableWebMvc注解用于在应用程序中启用Spring MVC,通过从WebMvcConfigurationSupport导入Spring MVC配置来工作。

The XML equivalent with similar functionality is <mvc:annotation-driven/>.

具有类似功能的XML对应物是<mvc:注释驱动/>.

The configuration can be customized by the @Configuration class implementing the WebMvcConfigurer:

配置可以由实现@Configuration类的WebMvcConfigurer定制。

@Configuration
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(
      List<HttpMessageConverter<?>> converters) {
 
        converters.add(new MyHttpMessageConverter());
    }
 
    // ...
}

3. @EnableCaching

3.@EnableCaching

The @EnableCaching annotation enables annotation-driven cache management capability within the application and allows us to use the @Cacheable and @CacheEvict annotations in our application.

@EnableCaching注解在应用程序中启用注解驱动的缓存管理能力,允许我们在应用程序中使用@Cacheable@CacheEvict注解

The XML equivalent with similar functionality is the <cache:*> namespace:

具有类似功能的XML对应物是<cache:*>命名空间。

@Configuration
@EnableCaching
public class CacheConfig {
 
    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(
          Arrays.asList(new ConcurrentMapCache("default")));
        return cacheManager;
    }
}

This annotation also has the following options:

该注释也有以下选项。

  • mode — indicates how caching advice should be applied
  • order — indicates the ordering of the execution caching advisor when applied at a specific joinpoint
  • proxyTargetClass — indicates whether subclass-based (CGLIB) proxies are to be created as opposed to standard Java interface-based proxies

This configuration again can be customized by the @Configuration class implementing the CachingConfigurerSupport class:

这个配置又可以通过实现@Configuration类的CachingConfigurerSupport类来定制。

@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {

    @Bean
    @Override
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(
          Arrays.asList(new ConcurrentMapCache("default")));
        return cacheManager;
    }

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new MyKeyGenerator();
    }
}

For more on using Spring caching you can refer to this article.

关于使用Spring缓存的更多信息,你可以参考这个文章

4. @EnableScheduling

4.@EnableScheduling

The @EnableScheduling annotation enables scheduled task capabilities and allows us to use @Scheduled annotations in the application. The XML equivalent with similar functionality is the <task:*> namespace using the scheduler attribute.

@EnableScheduling注解启用了计划任务功能,并允许我们在应用程序中使用@Scheduled注解。具有类似功能的XML对应物是使用<task:*>属性的scheduler命名空间。

This configuration again can be customized by the @Configuration class implementing the SchedulingConfigurer class:

这个配置又可以通过实现@Configuration类的SchedulingConfigurer类来定制。

@Configuration
@EnableScheduling
public class SchedulingConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(
      ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean(destroyMethod = "shutdown")
    public Executor taskExecutor() {
        return Executors.newScheduledThreadPool(100);
    }
}

For more on using Spring scheduling, you can refer to this article.

关于使用Spring调度的更多信息,你可以参考这篇文章

5. @EnableAsync

5.@EnableAsync

The @EnableAsync annotation enables asynchronous processing in our application. The XML equivalent with similar functionality is the <task:*> namespace using the executor attribute.

@EnableAsync注解在我们的应用程序中启用异步处理。具有类似功能的XML对应物是使用<task:*>属性的executor命名空间。

@Configuration
@EnableAync
public class AsyncConfig { ... }

For more on using Spring async, you can refer to this article.

关于使用Spring async的更多信息,你可以参考这篇文章

6. @EnableWebSocket

6.@EnableWebSocket

The @EnableWebSocket annotation is used to configure the processing of web socket requests. Customization can be done by implementing the WebSocketConfigurer class:

@EnableWebSocket注解用于配置Web socket请求的处理。可以通过实现WebSocketConfigurer类来进行定制。

@Configuration
@EnableWebSocket
public class MyConfiguration implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(echoWebSocketHandler(), "/echo").withSockJS();
    }

    @Bean
    public WebSocketHandler echoWebSocketHandler() {
        return new EchoWebSocketHandler();
    }
}

For more on using Spring Websockets, you can refer to this article.

关于使用Spring Websockets的更多信息,你可以参考这篇文章

7. @EnableJpaRepositories

7.@EnableJpaRepositories

The @EnableJpaRepositories annotation enables Spring Data JPA repositories by scanning the package of the annotated configuration class for repositories.

@EnableJpaRepositories注解通过扫描被注解的配置类的包来启用Spring Data JPA存储库

@Configuration
@EnableJpaRepositories
public class JpaConfig { ... }

Some options available for this annotation are:

该注释的一些可用选项是。

  • value — alias for the basePackages() attribute
  • basePackages — base packages to scan for annotated components
  • enableDefaultTransactions — configures whether or not to enable default transactions for Spring Data JPA repositories
  • entityManagerFactoryRef — configures the name of the EntityManagerFactory bean definition to be used

8. @EnableTransactionManagement

8.@EnableTransactionManagement

The @EnableTransactionManagement annotation enables Spring’s annotation-driven transaction management capability. The XML equivalent is the <tx:*> namespace.

@EnableTransactionManagement注解启用了Spring的注解驱动的事务管理能力。XML的等价物是<tx:*>命名空间。

@Configuration
@EnableTransactionManagement
public class JpaConfig { ... }

For more on using Spring Transaction Management, you can refer to this article.

关于使用Spring事务管理的更多信息,您可以参考这篇文章

9. @EnableJpaAuditing

9.@EnableJpaAuditing

The @EnableJpaAuditing annotation enables auditing on your JPA entities.

@EnableJpaAuditing注解在你的JPA实体上启用审计

@Configuration
@EnableJpaAuditing
public class JpaConfig {

    @Bean
    public AuditorAware<AuditableUser> auditorProvider() {
        return new AuditorAwareImpl();
    }
}

For more on using Spring Web Sockets, you can refer to this article.

关于使用Spring Web Sockets的更多信息,您可以参考此文章

10. Conclusion

10.结论

In this quick article, we looked at some @Enable Spring annotations and how they can be used to help us configure a Spring Application.

在这篇快速文章中,我们看了一些@Enable Spring注解,以及如何使用它们来帮助我们配置Spring应用程序。