我是手翻了幾乎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
在spring security中需要這樣的配置,去做系統權限的管理
@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();
}
}
@EnableWebMvcSecurity