@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
@Bean
@ComponentScan,可用于扫描Model,多模块的开发中会用到
@ComponentScans
@Conditional
@Configuration
@DependsOn
@Description
@EnableAspectJAutoProxy
@EnableLoadTimeWeaving
@EnableMBeanExport
@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
@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);
}
}
@TransactionalEventListener
@Transactional
@EnableTransactionManagement
@EnableKafka
@EnableKafkaStreams
@KafkaHandler
@KafkaListener
@KafkaListeners
@PartitionOffset
@TopicPartition
@Autowired
@Configurable
@Lookup
@Qualifier
@Value
@Required
@UsesJava7
@UsesJava8
@UsesSunHttpServer
@Order
@AliasFor
@EntityGraph
@Lock
@Query
@QueryHints
@Temporal
@Bindings
@EnableBinding,配合@StreamListener,可用于kafka的配置使用
@StreamListener
@Input
@Output
@StreamListener
@StreamMessageConverter
@StreamRetryTemplate
@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
@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 extends JpaRepository,
JpaSpecificationExecutor{
}
@RepositoryDefinition
@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
@BootstrapConfiguration
@RefreshScope
@EnableHystrix
@EnableEurekaClient
@ConditionalOnRibbonAndEurekaEnabled
@RibbonClient
@RibbonClientName
@RibbonClients
@ContinueSpan
@NewSpan
@SpanTag
@ClientSampler
@ServerSampler
@SpanName
@Classifier
@Backoff
@CircuitBreaker
@EnableRetry
@Recover
@Retryable
@EnableOAuth2Sso
@BeforeOAuth2Context
@OAuth2ContextConfiguration
@EnableGlobalAuthentication
@EnableGlobalMethodSecurity
@EnableReactiveMethodSecurity
@Secured
@PostAuthorize
@PostFilter
@PreAuthorize
@PreFilter
@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
@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/");
}
}
@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
@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