天天看點

Spring中的所有注解及其用途,總結2,太多太難,持續更

我是手翻了幾乎Spring所有包,去找的這些注解,Spring可能會缺漏,如果你們項目中還有其他Spring注解的使用,可留言給我,我再補充...共同學習

  • ​​一、spring-web​​
  • ​​二、spring-context​​
  • ​​三、spring-tx​​
  • ​​四、spring-kafka​​
  • ​​五、spring-beans​​
  • ​​六、spring-core​​
  • ​​七、spring-data-jpa​​
  • ​​八、spring.cloud.stream​​
  • ​​九、springboot.context​​
  • ​​十、spring-data-common​​
  • ​​十一、spring-cloud-common​​
  • ​​十二、spring-cloud.context​​
  • ​​十三、springframework.cloud.netflix​​
  • ​​十四、springframework.cloud.sleuth​​
  • ​​十五、org.springframework.retry​​
  • ​​十六、org.springframework.security/org.springframework.boot.autoconfigure.security​​
  • ​​十七、org.springframework.integration.*包下​​
  • ​​十八、spring.webMvc​​
  • ​​十九、spring-cloud-openfeign-core,這個包用于遠端過程調用的時候引入​​
  • ​​二十、spring-security-config​​

一、spring-web

@ControllerAdvice

@CookieValue,

@CrossOrigin,

@DeleteMapping,

@ExceptionHandler,

@GetMapping,

@InitBinder,

@Mapping,

@MatrixVariable,

@ModelAttribute,

@package,-info

@PatchMapping,

@PathVariable,

@PostMapping,

@PutMapping,

@RequestAttribute,

@RequestBody,

@RequestHeader,

@RequestMapping,

@RequestParam,

@RequestPart,

@ResponseBody,

@ResponseStatus,

@RestController,

@RestControllerAdvice,可作用,異常攔截捕獲

@RestControllerAdvice
@Slf4j
public class WebExceptionHandler {
/**
 * 參數類型轉換錯誤
 *
 * @param e
 * @return
 */
@ExceptionHandler(ConversionException.class)
public Object conversionException(ConversionException e) {
log.error(">>>異常:{}", JSONObject.toJSONString(e));
e.printStackTrace();
return ResultBean.error(HttpStatus.BAD_REQUEST.value() + "", e.getMessage());
}
}      

@SessionAttribute,

@SessionAttributes,

@SessionScope

@RequestScope

@ApplicationScope

這三個定義執行個體對象的時候,執行個體化方式,和Singleton      

二、spring-context

@Bean

@ComponentScan,可用于掃描Model,多子產品的開發中會用到

@ComponentScans

@Conditional

@Configuration

@DependsOn

@Description

@EnableAspectJAutoProxy

@EnableLoadTimeWeaving

@EnableMBeanExport

@Import

  • 該@Import注釋訓示一個或多個@Configuration類進口。
  • 導入的@Configuration類中聲明的@Bean定義應使用@Autowired注入進行通路。可以對bean本身進行自動裝配,也可以對聲明bean的配置類執行個體進行自動裝配。
  • 該@Import注解可以在類級别或作為元注解來聲明。

使用格式如下

@Configuration
public class ConfigA {

    @Bean
    public A a() {
        return new A();
    }
}

@Configuration
public class ConfigB {

    @Bean
    public B b() {
        return new B();
    }
}


@Configuration
@Import(value = {ConfigA.class, ConfigB.class})
public class ConfigD {

    @Bean
    public D d() {
        return new D();
    }
}      

@ImportResource

@Lazy

@Primary,定義多個資料源的時候,

@Configuration
public class DataSourceConfig {
    // 預設資料源 DB-1
    @Bean(name = "dataSourceCore")
    @ConfigurationProperties(prefix = "spring.datasource") // application.properteis中對應屬性的字首
    public DataSource dataSourceCore() {
        return DruidDataSourceBuilder.create().build();
    }

    // 資料源-DB-2
    @Bean(name = "dataSourceBiz")
    @ConfigurationProperties(prefix = "biz.datasource") // application.properteis中對應屬性的字首
    public DataSource dataSourceBiz() {
        return DruidDataSourceBuilder.create().build();
    }


    /**
     * 動态資料源: 通過AOP在不同資料源之間動态切換
    @SuppressWarnings({"rawtypes", "unchecked"})
    @Primary
    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 預設資料源
        dynamicDataSource.setDefaultTargetDataSource(dataSourceCore());
        // 配置多資料源
        Map<Object, Object> dsMap = new HashMap();
        dsMap.put("dataSourceCore", dataSourceCore());
        dsMap.put("dataSourceBiz", dataSourceBiz());

        dynamicDataSource.setTargetDataSources(dsMap);
        return dynamicDataSource;
    }
}      

@Profile

@PropertySource

@PropertySources

@Role

@Scope,這個值用于标注,單例或者prototype等

@ScopeMetadataResolver

@DateTimeFormat,用于Model定義時的,String 轉LocalDateTime,前端 傳時間類型 xxxx-xx-xx xx:xx:xx,可轉成LocaldateTime(2011-12-13T12:46:36)

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime tradeDate;      

@NumberFormat,可用于decimal的數值,轉換,前端可傳值(逗号分隔的數字)11,314.314可轉成11314.314

@NumberFormat(pattern = "#,###,###,###.##")
    private BigDecimal amount;      

@Component,标注元件(自動掃描),很多常見的@Controller,@Service,@Repository,@Configuration等都注入了這個注解

@Controller

@Indexed

@Repository,定義Dao層,注意和@NoRepositoryBean的配合使用(公共Repo的時候會用到)

@Service,常用于标注在接口實作類上,還有異步接口的管理(使用時注入UserService,就可排程此異步的具體實作)

@Service
public class UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    private final RestTemplate restTemplate;

    public UserService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    @Async("task1")
    public CompletableFuture <User> findUser(String user) throws InterruptedException {

        logger.info("Looking up " + user);
        String url = String.format("https://api.github.com/users/%s", user);
        User results = restTemplate.getForObject(url, User.class);

        //
        Thread.sleep(1000L);
        return CompletableFuture.completedFuture(results);
    }
}      

@Async

@EnableAsync

@EnableScheduling

@Scheduled

@Schedules

@EventListener,事件監聽,在微服務的學習中,我用這個注解,列印了所有已注冊的服務名

package com.example.bootiful.component;

import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Log4j2
@Component
public class DiscoveryClientListener {

    private final DiscoveryClient discoveryClient;

    public DiscoveryClientListener(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void useDiscoveryClient() {
        this.discoveryClient
                .getServices()
                .forEach(log::info);
    }
}      

三、spring-tx

@TransactionalEventListener

@Transactional

@EnableTransactionManagement

四、spring-kafka

@EnableKafka

@EnableKafkaStreams

@KafkaHandler

@KafkaListener

@KafkaListeners

@PartitionOffset

@TopicPartition

五、spring-beans

@Autowired

@Configurable

@Lookup

@Qualifier

@Value

@Required

六、spring-core

@UsesJava7

@UsesJava8

@UsesSunHttpServer

@Order

@AliasFor

七、spring-data-jpa

@EntityGraph

@Lock

@Query

@QueryHints

@Temporal

八、spring.cloud.stream

@Bindings

@EnableBinding,配合@StreamListener,可用于kafka的配置使用

@StreamListener

@Input

@Output

@StreamListener

@StreamMessageConverter

@StreamRetryTemplate

九、springboot.context

@ConfigurationProperties,用于定義掃描自定義在Yaml中的autoConfig

tonels:
   duckName: tonels configration test
   totalCount: 2

server:
  servlet:
    context-path: /tonels
  port: 8081      

注入時

@Configuration
@ConfigurationProperties(prefix="tonels")
@Data
public class DuckPorperties{
    private String duckName;
    private int  totalCount;
}      

使用時

@RequestMapping("/duck")
    public String duck() {
        /**
         * 自動裝配模式的配置檔案屬性。
         */
        return duckPorperties.getDuckName();
    }      

@ConfigurationPropertiesBinding

@DeprecatedConfigurationProperty

@EnableConfigurationProperties

@NestedConfigurationProperty

@Delimiter

@DurationFormat

@DurationUnit

@JsonComponent

十、spring-data-common

@AccessType

@CreatedBy

@CreatedDate

@Id

@LastModifiedBy

@LastModifiedDate

@package-info

@PersistenceConstructor

@Persistent

@QueryAnnotation

@ReadOnlyProperty

@Reference

@Transient

@TypeAlias

@Version,JPA中樂觀鎖的實作

定義在字段上,

@Version
private int version;      

@NoRepositoryBean

@NoRepositoryBean,定義公共庫的時候,會用到
public interface BaseRepository<T> extends JpaRepository<T, Long>, 
  JpaSpecificationExecutor<T>{

}      

@RepositoryDefinition

十一、spring-cloud-common

@EnableCircuitBreaker

@EnableDiscoveryClient,定義在啟動類上,作用于服務的注冊與發現,啟動會把該項目注冊到注冊中心

@SpringBootApplication
@EnableDiscoveryClient
public class Ams1Application {

    public static void main(String[] args) {
        SpringApplication.run(Ams1Application.class, args);
    }
}      

此處是,引自基于alibaba 的springcloud 的微服務實作的服務的注冊和發現。

@LoadBalanced,這個注解是在微服務間的調用過程中,可能會使用到這個注解(微服務間多種調用方式,這個不是必須的),關于其他的調用方式可以參考這個,​​點選這個​​

@EnableDiscoveryClient
@SpringBootApplication
public class Application {
  @Bean
  @LoadBalanced
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }
  public static void main(String[] args) {
    SpringApplication.run(Application.class);
  }
}      

使用的時候,

@Autowired
 RestTemplate restTemplate;
 @GetMapping("/consumer")
 public String dc() {
    return restTemplate.getForObject("http://eureka-client/client", String.class);
 }      

@SpringCloudApplication

十二、spring-cloud.context

@BootstrapConfiguration

@RefreshScope

十三、springframework.cloud.netflix

@EnableHystrix

@EnableEurekaClient

@ConditionalOnRibbonAndEurekaEnabled

@RibbonClient

@RibbonClientName

@RibbonClients

十四、springframework.cloud.sleuth

@ContinueSpan

@NewSpan

@SpanTag

@ClientSampler

@ServerSampler

@SpanName

十五、org.springframework.retry

@Classifier

@Backoff

@CircuitBreaker

@EnableRetry

@Recover

@Retryable

十六、org.springframework.security/org.springframework.boot.autoconfigure.security

@EnableOAuth2Sso

@BeforeOAuth2Context

@OAuth2ContextConfiguration

@EnableGlobalAuthentication

@EnableGlobalMethodSecurity

@EnableReactiveMethodSecurity

@Secured

@PostAuthorize

@PostFilter

@PreAuthorize

@PreFilter

十七、org.springframework.integration.*包下

@Aggregator

@BridgeFrom

@BridgeTo

@CorrelationStrategy

@Default

@EndpointId

@Filter

@Gateway

@GatewayHeader

@IdempotentReceiver

@InboundChannelAdapter

@IntegrationComponentScan

@MessageEndpoint

@MessagingGateway

@Payloads

@Poller

@Publisher

@ReleaseStrategy

@Role

@Router

@ServiceActivator

@Splitter

@Transformer

@UseSpelInvoker

@EnableIntegration

@EnableIntegrationManagement

@EnableMessageHistory

@EnablePublisher

@GlobalChannelInterceptor

@IntegrationConverter

@IntegrationManagedResource

@SecuredChannel

十八、spring.webMvc

@EnableWebMvc,常在Spring + JSP中使用

這裡用于定義web資源,路徑(相對和絕對路徑)

@Configuration
@EnableWebMvc
@ComponentScan("com.book.web")
public class WebConfig extends WebMvcConfigurerAdapter {
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img/**")
                .addResourceLocations("/static/images/");
        registry.addResourceHandler("/js/**").addResourceLocations("/static/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("/static/css/");
        registry.addResourceHandler("/html/**").addResourceLocations("/static/html/");
    }
}      

十九、spring-cloud-openfeign-core,這個包用于遠端過程調用的時候引入

@EnableFeignClients,啟動類上注解

@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class OpenFeinApplication {

    public static void main(String[] args) {
        SpringApplication.run(OpenFeinApplication.class, args);
    }
}      

@FeignClient,定義在遠端過程調用中的接口上

@FeignClient(name = "AMS1",fallback = RemoteHystrix.class)
public interface RemoteClient {
    @GetMapping("/ams1/open")
    String openFeign();
}      

這個調用類似請求,http://AMS1:注冊port/ams1/open

@SpringQueryMap

二十、spring-security-config

@EnableGlobalAuthentication

@EnableGlobalMethodSecurity

@EnableWebSecurity

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends JsonWebTokenSecurityConfig {
    @Override
    protected void setupAuthorization(HttpSecurity http) throws Exception {
        http.authorizeRequests()

                // allow anonymous access to /user/login endpoint
                .antMatchers("/user/login").permitAll()
                .antMatchers("/swagger/**").permitAll()
                .antMatchers("/web/**").permitAll()
                .antMatchers("/").permitAll()


                // authenticate all other requests
                .anyRequest().authenticated();
    }
}