一、启动注解 @SpringBootApplication

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
    // ... 此处省略源码
}

@SpringBootApplication是一个复合注解,包含了@SpringBootConfiguration,@EnableAutoConfiguration,@ComponentScan这三个注解

@SpringBootConfiguration 注解,继承@Configuration注解,主要用于加载配置文件

@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类, 并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中,并且实例名就是方法名。

@EnableAutoConfiguration 注解,开启自动配置功能

@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器。借助于Spring框架原有的一个工具类:SpringFactoriesLoader的支持,@EnableAutoConfiguration可以智能的自动配置功效才得以大功告成

@ComponentScan 注解,主要用于组件扫描和自动装配

@ComponentScan的功能其实就是自动扫描并加载符合条件的组件或bean定义,最终将这些bean定义加载到容器中。我们可以通过basePackages等属性指定@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现从声明@ComponentScan所在类的package进行扫描,默认情况下是不指定的,所以SpringBoot的启动类最好放在root package下。

@ServletComponentScan

在SpringBootApplication上使用@ServletComponentScan注解后,Servlet、Filter、Listener可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册,无需其他代码。

@MapperScan(“com.Vm.server”)

@MapperScan注解只会扫描包中的接口,不会扫描类,扫描指定包中的接口

@EnableScheduling: spring自带的定时服务

public class ScheduledTasks {
   @Scheduled(fixedRate = 1000 * 30) //每30秒执行一次
    public void reportCurrentTime(){
    	System.out.println ("Scheduling Tasks Examples: The time is now " + dateFormat().format (new Date ()));
	}
}

二、Controller 相关注解

@Controller 控制器,处理http请求。

@RestController 复合注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 * @since 4.0.1
	 */
	@AliasFor(annotation = Controller.class)
	String value() default "";
}

@RestController注解相当于@ResponseBody+@Controller合在一起的作用,RestController使用的效果是将方法返回的对象直接在浏览器上展示成json格式.

@RequestBody 通过HttpMessageConverter读取Request Body并反序列化为Object

@RequestMapping 将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上

@GetMapping用于将HTTP get请求映射到特定处理程序的方法注解

@RequestMapping(value = “/say”,method = RequestMethod.GET)等价于:@GetMapping(value = “/say”)

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {
//...
}

@GetMapping是@RequestMapping(method = RequestMethod.GET)的缩写

@PostMapping用于将HTTP post请求映射到特定处理程序的方法注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.POST)
public @interface PostMapping {
    //...
}

@PostMapping是@RequestMapping(method = RequestMethod.POST)的缩写

@PutMapping是@RequestMapping(method = RequestMethod.PUT)的简写

@DeleteMapping是@RequestMapping(method = RequestMethod.DELETE)的简写

三、取请求参数值

@PathVariable:获取url中的数据

@Controller
@RequestMapping("/User")
public class HelloWorldController {

    @RequestMapping("/getUser/{uid}")
    public String getUser(@PathVariable("uid")Integer id, Model model) {
        System.out.println("id:"+id);
        return "user";
    }
}

@RequestParam:获取请求参数的值

@Controller
@RequestMapping("/User")
public class HelloWorldController {
    @RequestMapping("/getUser")
    public String getUser(@RequestParam("uid")Integer id, Model model) {
        System.out.println("id:"+id);
        return "user";
    }
}

@RequestHeader 把Request请求header部分的值绑定到方法的参数上

@CookieValue 把Request header中关于cookie的值绑定到方法的参数上

四、注入bean相关

@Repository DAO层注解

DAO层中接口继承JpaRepository<T,ID extends Serializable>,需要在build.gradle中引入相关jpa的一个jar自动加载。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}

@Service

  • @Service是@Component注解的一个特例,作用在类上
  • @Service注解作用域默认为单例
  • 使用注解配置和类路径扫描时,被@Service注解标注的类会被Spring扫描并注册为Bean
  • @Service用于标注服务层组件,表示定义一个bean
  • @Service使用时没有传参数,Bean名称默认为当前类的类名,首字母小写
  • @Service(“serviceBeanId”)或@Service(value=”serviceBeanId”)使用时传参数,使用value作为Bean名字
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";
}

@Scope作用域注解

@Scope作用在类上和方法上,用来配置 spring bean 的作用域,它标识 bean 的作用域

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {

	/**
	 * Alias for {@link #scopeName}.
	 * @see #scopeName
	 */
	@AliasFor("scopeName")
	String value() default "";

	@AliasFor("value")
	String scopeName() default "";

	ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;
}
/*属性介绍*/
value
    singleton   表示该bean是单例的。(默认)
    prototype   表示该bean是多例的,即每次使用该bean时都会新建一个对象。
    request     在一次http请求中,一个bean对应一个实例。
    session     在一个httpSession中,一个bean对应一个实例。
    
proxyMode
    DEFAULT         不使用代理。(默认)
    NO              不使用代理,等价于DEFAULT。
    INTERFACES      使用基于接口的代理(jdk dynamic proxy)。
    TARGET_CLASS    使用基于类的代理(cglib)

@Entity实体类注解

@Table(name =“数据库表名”),这个注解也注释在实体类上,对应数据库中相应的表

@Id、@Column注解用于标注实体类中的字段,pk字段标注为@Id,其余@Column

@Bean产生一个bean的方法

@Bean明确地指示了一种方法,产生一个bean的方法,并且交给Spring容器管理。支持别名@Bean(“xx-name”)

@Autowired 自动导入

  • @Autowired注解作用在构造函数、方法、方法参数、类字段以及注解上
  • @Autowired注解可以实现Bean的自动注入

@Component

把普通pojo(对象)实例化到spring容器中,相当于配置文件中的

@Component就是告诉spring,我是pojo类,把我注册到容器中吧,spring会自动提取相关信息

@Configuration

可理解为用spring的时候xml里面的标签,用@Configuration注解该类,等价 与XML中配置beans

@Configuration    
		public class ExampleConfiguration {    
		    
		    @Value("com.mysql.jdbc.Driver")    
		    private String driverClassName;    
		    
		    @Value("jdbc://xxxx.xx.xxx/xx")    
		    private String driverUrl;    
		    
		    @Value("${root}")    
		    private String driverUsername;    
		    
		    @Value("123456")    
		    private String driverPassword;    
		    
		    @Bean(name = "dataSource")    
		    public DataSource dataSource() {    
		        BasicDataSource dataSource = new BasicDataSource();    
		        dataSource.setDriverClassName(driverClassName);    
		        dataSource.setUrl(driverUrl);    
		        dataSource.setUsername(driverUsername);    
		        dataSource.setPassword(driverPassword);    
		        return dataSource;    
		    }   
            @Bean    
		    public PlatformTransactionManager transactionManager() {    
		        return new DataSourceTransactionManager(dataSource());    
		    }    
        }

五、导入配置文件

@PropertySource注解

引入单个properties文件:

@PropertySource(value = {“classpath : xxxx/xxx.properties”})

引入多个properties文件:

@PropertySource(value = {“classpath : xxxx/xxx.properties”,“classpath : xxxx.properties”})

@ImportResource导入xml配置文件

可以额外分为两种模式 相对路径classpath,绝对路径(真实路径)file

相对路径(classpath)

  • 引入单个xml配置文件:@ImportSource(“classpath : xxx/xxxx.xml”)
  • 引入多个xml配置文件:@ImportSource(locations={“classpath : xxxx.xml” , “classpath : yyyy.xml”})

绝对路径(file)

  • 引入单个xml配置文件:@ImportSource(locations= {“file : d:/hellxz/dubbo.xml”})
  • 引入多个xml配置文件:@ImportSource(locations= {“file : d:/hellxz/application.xml” , “file : d:/hellxz/dubbo.xml”})

取值:使用@Value注解取配置文件中的值

@Value("${properties中的键}")

//属性

private String xxx;

@Import 导入额外的配置信息

功能类似XML配置的,用来导入配置类,可以导入带有@Configuration注解的配置类或实现了ImportSelector/ImportBeanDefinitionRegistrar

@SpringBootApplication
@Import({SmsConfig.class})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

六、事务注解 @Transactional

事务有两种实现方式,分别是编程式事务管理和声明式事务管理两种方式

  • 编程式事务管理使用TransactionTemplate或者直接使用底层的PlatformTransactionManager。对于编程式事务管理,spring推荐使用TransactionTemplat
  • 建立在AOP之上的。其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务,通过@Transactional就可以进行事务操作

七、全局异常处理

@ControllerAdvice 统一处理异常

@ControllerAdvice 注解定义全局异常处理类

@ControllerAdvice
public class GlobalExceptionHandler {
}

@ExceptionHandler 注解声明异常处理方法

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleException(){
        return "Exception Deal!";
    }
}

@SpringBootApplication,替代@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan
@ImportAutoConfiguration,导入配置类,一般做测试的时候用,正常优先使用@EnableAutoConfiguration
@SpringBootConfiguration,替代@Configuration
@ImportResource,将资源导入容器中
@PropertySource,导入properties文件
@PropertySources,@PropertySource的集合
@Role,bean角色定义ROLE_APPLICATION(默认值)、ROLE_SUPPORT(辅助角色)、ROLE_INFRASTRUCTURE(后台角色,用户无感)
@Scope,指定bean的作用域,默认singleton,其他包括prototype、request、session、globalSession
@Lazy,使bean懒加载,取消bean预初始化。用法:bean注册的地方加上@Lazy和用的地方加上@Lazy
@Primary,自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
@Profile,指定bean在哪个环境被激活
@DependsOn,依赖的bean注册完成,才注册当前类,依赖bean不存在会报错。用于控制bean加载的顺序
@PostConstruct,bean的属性都注入完之后,执行注解标注的方法进行初始化工作
@Autowired, 默认按类型装配,如果我们想使用按名称装配,可以结合@Qualifier注解一起使用
@Lookup,根据方法返回的类型,去容器中捞出对应的bean。适合单例作用域引用非单例的情况。
@Qualifier,申明bean名字,且可以按bean名字加载bean
@Required,检查bean的属性setXXX()方法,要求属性在配置阶段必须已配置
@Value,值注入,@Value("${xxx}")注入配置文件中的值;@Value("#{xxx}")支持spel,可注入bean、常量等
@SpringBootConfiguration,包装@Configuration
@Description,添加bean的文字描述
@EnableAspectJAutoProxy,启动AspectJ自动代理
@EnableLoadTimeWeaving,启用类加载器动态增强功能,使用Instrumentation实现
@AutoConfigurationPackage,包含该注解的package会被AutoConfigurationPackages注册
@AutoConfigureBefore,在指定配置类初始化前加载
@AutoConfigureAfter,在指定配置类初始化后加载
@AutoConfigureOrder,指定配置类初始化顺序,越小初始化越早

组件注册
@ComponentScans,@ComponentScan集合
@ComponentScan,扫描启动类目录下的所有符合条件的Bean,并注入容器
@Component,泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注
@Controller,用于标注控制层组件
@Repository,用于标注数据访问组件,即DAO组件
@Service,用于标注业务层组件
@Configuration,表名类里的包含@Bean注解标注的方法
@Bean,用在@Configuration和@Component注解下的类里面的方法上。@Configuration类里面,@Bean注解的方法被类中其他方法调用时,会注入bean而不会执行方法本身;@Component类里面,@Bean注解的方法被类中其他方法调用时,会执行方法本身,不会注入bean;被注解的方法如果是静态(static),bean的注册时间可能比所在类的注册时间早。
@EnableAutoConfiguration,开启自动注册配置文件,例如会去META-INF/spring.factories找需要自动转载的类
@Import,将class导入容器中

选择器
@Conditional,当指定的条件都满足时,组件才被注册
@ConditionalOnBean,指定bean在上下文中时,才注册当前bean。用在方法上,则默认依赖类为方法的返回类型
@ConditionalOnClass,指定类在classpath上时,才初始化当前bean。用在方法上,则默认依赖类为方法的返回类型
@ConditionalOnCloudPlatform,在指定云平台才注册配置
@ConditionalOnExpression,指定spel为true时注册配置
@ConditionalOnJava,在指定java版本时注册配置
@ConditionalOnJndi
@ConditionalOnMissingBean,指定bean不在上下文中时,才初始化当前bean。用在方法上,则默认依赖类为方法的返回类型
@ConditionalOnMissingClass,指定类不在classpath上时,才初始化当前bean。用在方法上,则默认依赖类为方法的返回类型
@ConditionalOnNotWebApplication,不是在web环境才注册配置
@ConditionalOnProperty,配置文件中的值与指定值是否相等,相等才注册配置
@ConditionalOnResource,指定resources都在classpath上才注册配置
@ConditionalOnSingleCandidate,上下文中只有一个候选者bean时才注册配置
@ConditionalOnWebApplication,是在web环境才注册配置
缓存
@EnableCaching,开启缓存配置,支持子类代理或者AspectJ增强
@CacheConfig,在一个类下,提供公共缓存配置
@Cacheable,放着方法和类上,缓存方法或类下所有方法的返回值
@CachePut,每次先执行方法,再将结果放入缓存
@CacheEvict,删除缓存
@Caching,可以配置@Cacheable、@CachePut、@CacheEvict

定时器
@EnableScheduling,开启定时任务功能
@Scheduled,按指定执行周期执行方法
@Schedules,包含多个@Scheduled,可同时运行多个周期配置
@EnableAsync,开启方法异步执行的能力,通过@Async或者自定义注解找到需要异步执行的方法。通过实现AsyncConfigurer接口的getAsyncExecutor()和getAsyncUncaughtExceptionHandler()方法自定义Executor和异常处理。
@Async,标记方法为异步线程中执行
注入配置文件properties
@EnableConfigurationProperties,启动@ConfigurationProperties功能
@ConfigurationProperties,将properties文件里的内容,自动注入bean对应的属性中
@DeprecatedConfigurationProperty,用在配置文件的getter()方法上,标记字段已经过期,并提示替换的字段。一般给spring-boot-configuration-processor使用。
@NestedConfigurationProperty,标记在配置文件的字段上,提示spring-boot-configuration-processor,配置包含嵌套的配置。
spring-configuration-metadata.json 提供配置的元信息,在写properties配置时,会有语法提示。在项目中引入spring-boot-configuration-processor项目,会扫描@ConfigurationProperties注解,自动生成spring-configuration-metadata.json

@Configuration把一个类作为一个IoC容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean。

@Scope注解 作用域

@Lazy(true) 表示延迟初始化

@Service用于标注业务层组件、

@Controller用于标注控制层组件(如struts中的action)

@Repository用于标注数据访问组件,即DAO组件。

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

@Scope用于指定scope作用域的(用在类上)

@PostConstruct用于指定初始化方法(用在方法上)

@PreDestory用于指定销毁方法(用在方法上)

@Resource 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。

@DependsOn:定义Bean初始化及销毁时的顺序

@Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常

@Autowired 默认按类型装配,如果我们想使用按名称装配,可以结合@Qualifier注解一起使用

@Autowired @Qualifier(“personDaoBean”) 存在多个实例配合使用

@Deprecated 简单来讲就是,若某类或某方法加上该注解之后,表示此方法或类不再建议使用,调用时也会出现删除线,但并不代表不能用,只是说,不推荐使用,因为还有更好的方法可以调用。

************************************************

@RestController //将返回的数据转化成Json格式

@RequestMapping //可以在类或者方法上使用。在类的级别上注解会将一个特定请求或者请求模式映射到一个控制器之上,之后还可以另外添加方法级别的注解进一步指定到处理方法的映射关系

@Autowired //自动装配,其作用是为了消除代码Java里面的getter/setter与bean属性中的property。当然,getter看个人需求,如果私有属性需要对外提供的话,应当予以保留

@GetMapping //顾名思义,Get请求

@PostMapping //Post请求

@Service //用于标注业务层组件,也就是把当前类注册成为Spring的Bean

@Controller //用于标注控制层组件,如status中的actin

@Repositroy //用于标注数据访问组件,即DAO组件

@Compoent //当这个组件不好归类时,我们可以使用这个注解,把当前类注册成为Spring的Bean

@PropertySource //配置属性资源文件地址

@ConfigurationProperties(prefix=“xxx”) //配置yml或者properties文件引用前缀

************************************************

@Data //基于lombok,意思是设置Getter(),Setter()方法并生成toString()、equerys()等

@Setter //在model类中不需要写set()方法了,直接加这个注解就可以了

@Getter //在model类中不需要写get()方法了,直接加这个注解就可以了

@AllArgsConstructor //生成带全部参数的构造方法

@NoArgsConstructor //生成不带任何参数的构造方法

@Builder //声明实体,表示可以进行Builder方式初始化

@Slf4J //等价于开启loger对象,可以直接log.info()写入日志

@Mapper //添加了@Mapper注解之后这个接口在编译时会生成相应的实现类,需要注意的是:这个接口中不可以定义同名的方法,因为会生成相同的id,也就是说这个接口是不支持重载的

更多推荐

Java SpringBoot 常用注解汇总