部分注解记录2

•@SpringBootApplication
是一个组合注解(组合注解可以自定义,包含所有引入注解功能)。定义在main方法入口类处,用于启动spring boot项目

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@Configuration@EnableAutoConfiguration@ComponentScanpublic @interface SpringBootApplication { /** * Exclude specific auto-configuration classes such that they will never be applied. * @return the classes to exclude */ Class<?>[] exclude() default {};}
•@EnableAutoConfiguration
让spring boot容器根据类路径中的jar包依赖当前项目进行自动配置,文件在src/main/resources的META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\org.springframework.boot.autoconfigure.aop.AopAutoConfiguration若有多个自动配置,用“,”隔开
•@ImportResource
加载xml配置,一般是放在启动main类上

@ImportResource(“classpath*:/spring/.xml") 单个@ImportResource({"classpath:/spring/1.xml”,“classpath*:/spring/2.xml”}) 多个
•@Value
application.properties定义属性,直接使用@Value注入即可

public class A{ @Value("${push.start:0}") //如果缺失,默认值为0 private Long id;}
•@ConfigurationProperties(prefix=“person”)
可以新建一个properties文件,ConfigurationProperties的属性prefix指定properties的配置的前缀,通过location指定properties文件的位置

@ConfigurationProperties(prefix=“person”)public class PersonProperties { private String name ; private int age;}//注解也可以用在方法上@Configuration@ConditionalOnProperty(name = “synchronize”, havingValue = “true”)public class SecondDatasourceConfig { @Bean(name = “SecondDataSource”) @Qualifier(“SecondDataSource”) @ConfigurationProperties(prefix = “spring.second.datasource”) public DataSource jwcDataSource() { return DataSourceBuilder.create().build(); }}
•@EnableConfigurationProperties
用 @EnableConfigurationProperties注解使 @ConfigurationProperties生效,并从IOC容器中获取bean。@SpringBootApplication 内部已经包含该注解
https://blog.csdn.net/u010502101/article/details/78758330
•@RestController
组合@Controller和@ResponseBody,当你开发一个和页面交互数据的控制时,比如bbs-web的api接口需要此注解
•@RequestMapping("/api2/copper")
用来映射web请求(访问路径和参数)、处理类和方法,可以注解在类或方法上。注解在方法上的路径会继承注解在类上的路径。
@RequestMapping(value="/api2/copper",produces=“application/json;charset=UTF-8”,method = RequestMethod.POST)//produces属性:定制返回的response的媒体类型和字符集,或需返回值是json对象
•@RequestParam
获取request请求的参数值
public List getOpList(HttpServletRequest request, @RequestParam(value = “pageIndex”, required = false) Integer pageIndex, @RequestParam(value = “pageSize”, required = false) Integer pageSize) {。。。。}
•@PathVariable
用来获得请求url中的动态参数

@Controller public class TestController { @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET) public String getLogin(@PathVariable(“userId”) String userId, @PathVariable(“roleId”) String roleId){ System.out.println("User Id : " + userId); System.out.println("Role Id : " + roleId); return “hello”; } }
•@ResponseBody
支持将返回值放在response体内,而不是返回一个页面。比如Ajax接口,可以用此注解返回数据而不是页面。此注解可以放置在返回值前或方法前。

另一个玩法,可以不用@ResponseBody。继承FastJsonHttpMessageConverter类并对writeInternal方法扩展,在spring响应结果时,再次拦截、加工结果// stringResult:json返回结果//HttpOutputMessage outputMessage byte[] payload = stringResult.getBytes(); outputMessage.getHeaders().setContentType(META_TYPE); outputMessage.getHeaders().setContentLength(payload.length); outputMessage.getBody().write(payload); outputMessage.getBody().flush();
•@Bean(name=“bean的名字”,initMethod=“初始化时调用方法名字”,destroyMethod=“close”)
定义在方法上,用于容器内初始化一个bean实例。如果不指定name,默认名称是方法名

@Bean(destroyMethod=“close”)@ConditionalOnMissingBeanpublic PersonService registryService() { return new PersonService();}
•@Controller
在表现层(Spring MVC)使用
•@Service
在业务逻辑层(service层)使用
•@Repository
在数据访问层(dao层)使用
•@Component
泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。用于Class、interface、enum上
•@PostConstruct
spring容器初始化时,要执行该方法

@PostConstruct public void init() { 。。。。。}
•@ComponentScan
告知Spring扫描指定的包来初始化容器

@SpringBootApplication@ComponentScan( basePackages = {“cn.tomge.spider.operator.controller”, “cn.tomge.spider.operator.service”, “cn.tomge.spider.operator.listener”, “cn.tomge.spider.operator.storage”, “cn.tomge.spider.operator.config”, “cn.tomge.spider.operator.manager”})@ImportResource(“classpath*:/spring/**/*.xml”)@EnableSchedulingpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
•@Autowired
按类型注入,在默认情况下使用 @Autowired 注释进行自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个。当找不到一个匹配的 Bean 时,Spring 容器将抛出 BeanCreationException 异常,并指出必须至少拥有一个匹配的 Bean。
当不能确定 Spring 容器中一定拥有某个类的 Bean 时,可以在需要自动注入该类 Bean 的地方可以使用 @Autowired(required = false),这等于告诉 Spring:在找不到匹配 Bean 时也不报错
•@Resource

按名字注入
•@Primary
自动装配时,如果出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
https://www.jianshu.com/p/b0644c13a964
•@Configuration
声明当前类是一个配置类,相当于一个spring的 xml文件。这意味着这个类里可能有0个或者多个@Bean注解

@Configuration(“name”)//表示这是一个配置类,可以给这个配置类也起一个名称@ComponentScan(“spring4”)//类似于xml中的<context:component-scan base-package=“spring4”/>public class Config { @Autowired//自动注入,如果容器中有多个符合的bean时,需要进一步明确 @Qualifier(“compent”)//进一步指明注入bean名称为compent的bean private Compent compent; @Bean//类似于xml中的 public Compent newbean(){ return new Compent(); } }
•@Import
帮助我们将多个配置文件(可能是按功能分,或是按业务分)导入到一个主配置中,以避免将所有配置写在一个配置文件中
https://segmentfault.com/a/1190000011068471

@Configurationpublic class CDConfig { @Bean public CompactDisc compactDisc() { return new CompactDisc(); }}@Configuration@Import(CDConfig.class) //加载CDConfig配置,并对其内部的定义bean实例化public class CDPlayerConfig { @Bean(name = “cDPlayer”) public CDPlayer cdPlayer(CompactDisc compactDisc) { // 容器会自动注入CompactDisc类型的bean return new CDPlayer(compactDisc); }}
•@Order
@Order(1),值越小优先级超高,越先执行
•@ConditionalOnExpression
开关为true的时候才实例化bean,后面是默认值

@Configuration@ConditionalOnExpression("${enabled:false}")public class BigpipeConfiguration { @Bean public OrderMessageMonitor orderMessageMonitor(ConfigContext configContext) { return new OrderMessageMonitor(configContext); }}
•ConditionalOnWebApplication
当前项目是WEB项目的条件下才执行
https://www.jianshu.com/p/23f504713b94
•@ConditionalOnNotWebApplication
与上面正好相反
•@ConditionalOnProperty
根据application.properties里面的值,来匹配@ConditionalOnProperty,决定要不要执行该类。也是一种条件判断
https://blog.csdn.net/dalangzhonghangxing/article/details/78420057

@Configuration@ConditionalOnClass({ SitePreferenceHandlerInterceptor.class, SitePreferenceHandlerMethodArgumentResolver.class })@AutoConfigureAfter(DeviceResolverAutoConfiguration.class)@ConditionalOnProperty(prefix = “spring.mobile.sitepreference”, name = “enabled”, havingValue = “true”, matchIfMissing = true)@ConditionalOnWebApplicationpublic class SitePreferenceAutoConfiguration { @Bean @ConditionalOnMissingBean(SitePreferenceHandlerInterceptor.class) public SitePreferenceHandlerInterceptor sitePreferenceHandlerInterceptor() { return new SitePreferenceHandlerInterceptor(); }}
•@ConditionalOnClass
当类路径下有指定的类的条件下,才会执行

@Configuration@ConditionalOnClass({Gson.class})public class GsonAutoConfiguration { public GsonAutoConfiguration() { } @Bean @ConditionalOnMissingBean public Gson gson() { return new Gson(); }}
•@ConditionalOnMisssingClass({ApplicationManager.class})
该注解参数对应的类在classPath不存在,才会执行
•ConditionalOnBean
是否执行依赖于参数里的bean是否已经在容器里已经创建

@Configuration@ConditionalOnBean({LoadBalancerClient.class})@EnableConfigurationProperties({LoadBalancerRetryProperties.class})public class LoadBalancerAutoConfiguration {。。。}//只有 LoadBalancerClient类创建的bean对象在容器中存在时,才会执行LoadBalancerAutoConfiguration中的配置类
•@ConditionOnMissingBean(name = “example”)
如果name为“example”的bean不存在时,该注解修饰的代码块才执行
•@AutoConfigureAfter
在指定的配置类初始化后再加载
•@AutoConfigureBefore
在指定的配置类初始化前加载
•@AutoConfigureOrder
数越小越先初始化
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
•@Async
表明该方法是个异步方法,如果注解在类级别,表明该类所有的方法都是异步方法。
https://www.cnblogs.com/yun965861480/p/7505112.html

//指定线程池执行器@Async(“otherExecutor”)void doSomething(String s) { // this will be executed asynchronously by “otherExecutor”}
•@EnableAsync
开启对异步任务的支持,与 @Async 一块使用
https://www.e-learn.cn/content/java/479774
•@Scheduled
声明方法是一个定时任务。
https://www.jianshu.com/p/4d9c9b08111d

@Scheduled(fixedRate = 5000) // 表示 每隔 5000 毫秒执行一次public void reportCurrentTime() { System.out.println(“每隔五秒钟执行一次:” + dateFormat.format(new Date()));}
•@EnableScheduling
开启对定时任务的支持,与@Scheduled 一块使用
•@Transactional
可以在方法上,也可以注解在类上,当注解在类上的时候意味着此类的所有public方法都是开启事务的。
https://blog.csdn.net/nextyu/article/details/78669997
•@EventListener
在spring4.2版中,允许在任一bean的对应方法上注解@EventListener来标记该bean实现了listener方法。实现更大程度的解耦
https://blog.csdn.net/xixingzhe2/article/details/84070702

@Componentpublic class MyListener { private Logger logger = LoggerFactory.getLogger(getClass()); @EventListener public void handleDemoEvent(MyEvent event) { logger.info(“发布的data为:{}”, event.getData()); }}
•@EnableZuulProxy
路由网关的主要目的是为了让所有的微服务对外只有一个接口,我们只需访问一个网关地址,即可由网关将所有的请求代理到不同的服务中。Spring Cloud是通过Zuul来实现的,支持自动路由映射到在Eureka Server上注册的服务。Spring Cloud提供了注解@EnableZuulProxy来启用路由代理。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值