Spring中的所有注解及其用途,总结2,太多太难,持续更

编程入门 行业动态 更新时间:2024-10-27 02:24:08

我是手翻了几乎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-mon十一、spring-cloud-mon十二、spring-cloud.context十三、springframework.cloud.netflix十四、springframework.cloud.sleuth十五、.springframework.retry十六、.springframework.security/.springframework.boot.autoconfigure.security十七、.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 {@Beanpublic A a() {return new A();}
}@Configuration
public class ConfigB {@Beanpublic B b() {return new B();}
}@Configuration
@Import(value = {ConfigA.class, ConfigB.class})
public class ConfigD {@Beanpublic 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("api.github./users/%s", user);User results = restTemplate.getForObject(url, User.class);//Thread.sleep(1000L);return CompletableFuture.pletedFuture(results);}
}

@Async
@EnableAsync
@EnableScheduling
@Scheduled
@Schedules
@EventListener,事件监听,在微服务的学习中,我用这个注解,打印了所有已注册的服务名

package .example.bootiful.ponent;import lombok.extern.log4j.Log4j2;
import .springframework.boot.context.event.ApplicationReadyEvent;
import .springframework.cloud.client.discovery.DiscoveryClient;
import .springframework.context.event.EventListener;
import .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 testtotalCount: 2server:servlet:context-path: /tonelsport: 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-mon

@AessType
@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-mon

@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@LoadBalancedpublic RestTemplate restTemplate() {return new RestTemplate();}public static void main(String[] args) {SpringApplication.run(Application.class);}
}

使用的时候,

 @AutowiredRestTemplate restTemplate;@GetMapping("/consumer")public String dc() {return restTemplate.getForObject("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

十五、.springframework.retry

@Classifier
@Backoff
@CircuitBreaker
@EnableRetry
@Recover
@Retryable

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

@EnableOAuth2Sso
@BeforeOAuth2Context
@OAuth2ContextConfiguration
@EnableGlobalAuthentication
@EnableGlobalMethodSecurity
@EnableReactiveMethodSecurity
@Secured
@PostAuthorize
@PostFilter
@PreAuthorize
@PreFilter

十七、.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(".book.web")
public class WebConfig extends WebMvcConfigurerAdapter {@Beanpublic ViewResolver viewResolver() {InternalResourceViewResolver resolver = new InternalResourceViewResolver();resolver.setPrefix("/WEB-INF/views/");resolver.setSuffix(".jsp");return resolver;}@Overridepublic void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {configurer.enable();}@Overridepublic 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();
}

这个调用类似请求,AMS1:注册port/ams1/open
@SpringQueryMap

二十、spring-security-config

@EnableGlobalAuthentication
@EnableGlobalMethodSecurity
@EnableWebSecurity

在spring security中需要这样的配置,去做系统权限的管理

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends JsonWebTokenSecurityConfig {@Overrideprotected void setupAuthorization(HttpSecurity http) throws Exception {http.authorizeRequests()// allow anonymous aess to /user/login endpoint.antMatchers("/user/login").permitAll().antMatchers("/swagger/**").permitAll().antMatchers("/web/**").permitAll().antMatchers("/").permitAll()// authenticate all other requests.anyRequest().authenticated();}
}

@EnableWebMvcSecurity

更多推荐

太多,注解,太难,用途,Spring

本文发布于:2023-05-20 18:54:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/154786.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:太多   注解   太难   用途   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!