1. Overview

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.

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

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

2. @EnableWebMvc

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

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

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

@Configuration
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {

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

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.

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

@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
@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.

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.

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

@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.

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.

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

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

6. @EnableWebSocket

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

@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.

7. @EnableJpaRepositories

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

@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

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

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

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

9. @EnableJpaAuditing

The @EnableJpaAuditing annotation enables auditing on your JPA entities.

@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.

10. Conclusion

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


« 上一篇: gPRC 介绍