Sping注解

3 篇文章 0 订阅
3 篇文章 0 订阅
  • @Configuration
        @Configuration作用类似于spring-bean.xml中的<beans></beans>标签的作用,类似IOC容器,主要用于bean的注入,放置在类名上。使用该注解注入Bean后,获取IOC容器的方式不再使用ClassPathXmlApplicationContext或者文件系统路径来获取对应的IOC容器,而是使用 AnnotationConfigApplicationContext(AnnotationConfiguration.class)的方式来获取IOC容器(AnnotationConfiguration为自定义的配置类)
//Book类代码:
public class Book {
    private String name;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Book()
    {
        System.out.println("Book无参构造器");
    }
    public Book(String name) {
        super();
        this.name = name;
        System.out.println("有参构造器");
    }
    @Override
    public String toString() {
        return "Book-->    [name=" + name + "]";
    }
}
//自定义的配置类
@Configuration
public class AnnotationConfiguration {
    public AnnotationConfiguration() {
        System.out.println("初始化");
    }
    @Bean
    public Book book()
    {
        Book book=new Book();
        book.setName("C++");
        return book;
    }
}
//测试代码:
AnnotationConfigApplicationContext acac=
                new AnnotationConfigApplicationContext(AnnotationConfiguration.class);
        Book book=(Book) acac.getBean("book");
        System.out.println(book);
  • @ConfigurationProperties
        @ConfigurationProperties是一个外部化配置注解,比如外部的 .properties 属性文件。使用该注解,可以实现把外部的属性绑定到Bean实例,也可以实现在绑定的过程对外部属性进行合法性验证。
        @ConfigurationProperties通常放在类上使用,比如:
       @ConfigurationProperties(prefix = "student",ignoreInvalidFields = false,ignoreUnknownFields = false)
        public class StudentProperties {}
     也可以放在@Configuration注解类里面的@bean注解的方法上,比如:
      @Configuration
       public class TeacherConfig {
           @Bean
           @ConfigurationProperties(prefix = "teacher")
            public Teacher teacher(){
               //Spring会把@ConfigurationProperties注解的外部配置绑定到new Teacher()生成的实例对应属性上
            return new Teacher();
           }
      }
      注意事项:@ConfigurationProperties注解不会实例化bean,也不会把实例化后的bean加入到IOC容器中,只会对实例化后的bean对象进行属性绑定和属性值合法性校验。因此, @ConfigurationProperties注解不能单独使用,必须配合其他实列bean并把bean加入到IOC容器的注解一起使用,方案有三种:
    其一:@ConfigurationProperties+@Component/@Configuration
     @Configuration 
@ConfigurationProperties ( prefix  = "" ) 
public class   StudentProperties { }
   其二:@ConfigurationProperties+@EnableConfigurationProperties(Xxx.class)
     @ConfigurationProperties(prefix = "")
    public class StudentProperties {}
    @EnableConfigurationProperties(StudentProperties.class)
    @SpringBootApplication
     public class ConfigurationPropertiesApplication implements ApplicationRunner {
        @Autowired
        private StudentProperties studentProperties;
        @Override
        public void run(ApplicationArguments args) throws Exception {
            System.out.println(studentProperties.toString());
         }
    }
  其三:@ConfigurationProperties+@ConfigurationPropertiesScan
    @ConfigurationProperties(prefix = "student",ignoreInvalidFields = false,ignoreUnknownFields = false)
      public class StudentProperties {}
      @ConfigurationPropertiesScan
      @SpringBootApplication
      public class ConfigurationPropertiesApplication implements ApplicationRunner {
           @Autowired
           private StudentProperties studentProperties;
           @Override
            public void run(ApplicationArguments args) throws Exception {
               System.out.println(studentProperties.toString());
            }
       }
  • @MapperScan
                扫描指定包下的所有mapper类作为Mapper映射⽂件
                @MapperScan("com.demo.mapper"):扫描指定包中的接口
                @MapperScan("com.demo. .mapper"):一个 代表任意字符串,但只代表一级包,比如可以扫到com.demo.aaa.mapper,不能扫到                        com.demo.aaa.bbb.mapper
                @MapperScan("com.demo.* .mapper"):两个 代表任意个包,比如可以扫到com.demo.aaa.mapper,也可以扫com.demo.aaa.bbb.mapper
  • @Mapper
                 使用 @Mapper,最终 Mybatis 会有一个拦截器,会自动的把 @Mapper 注解的接口生成 动态代理类
当然,前提是,映射器(Mapper.xml)必须满足动态代理的条件: 1.namespace与接口的全限定类名相同
2.id名与接口中方法名一致
  • @Import  导入,把类注入到springIOC容器里
  • @interface 用于声明注解类的关键字,使用该注解自动继承 java.lang.annotation.Annotation类,该过程由编译器自动完成,须注意:在自定义注解时不可继承其他接口或者注解
  • @Target   该注解用于定义注解的目标范围,即注解可以用在什么地方
  • @Inherited  默认情况下,我们自定义的注解作用在父类上不会被子类继承,如果想让子类继承,则在自定义注解时需设置@Inherited
  • @Retention   注解的注解,称为元注解,该注解用于定义注解保留策略,即定义注解在什么时候存在。@retention注解有个一个属性value,是retentionpolicy枚举类型,决定了retention注解应该如何去保持,retention有3个值:CLASS(注解会保留到class文件,当class文件被load时被遗弃)、RUNNING(注解不仅被保留到class文件中,load之后仍然存在)、SOURCE(注解只保留在源文件中,编译时注解会被遗弃),生命周期长度:SOURCE<CLASS<RUNNING
  • @Aspect  该注解用于类上,标识该类为切面供容器读取
  • @Ponitcut 该注解作用于方法上,标识为切面的触发条件。每个Pointcut的定义包括2部分,⼀是表达式,⼆是⽅法签名。⽅法签名必须是public及void型。可以将Pointcu 中的⽅法看作是⼀个被Advice引⽤的助记符,因为表达式不直观,因此我们可以通过⽅法签名的⽅式为此表达式命名。因此Pointcut中的⽅法只需要⽅法签名, ⽽不需要在⽅法体内编写实际代码。
  • @Around  环绕增强,相当于MethodInterceptor
  • @AfterReturning 后置增强,方法正常退出时执行
  • @Before 前置增强
  • @AfterThrowing 异常抛出增强,异常抛出时执行
  • @After final增强,不管是异常抛出还是正常退出都执行
  • @Documented  该注解用于描述其他类型的 annotation应该被javadoc文档化,出现在api doc中
  • @SuppressWarnnings  该注解告诉编译器忽略某类编译告警
  • @Component  泛指各种组件
             web开发,提供3个@Component注解衍生注解(功能一样)取代
                 @Repository (“名称”):dao层 数据访问层
                 @Service (“名称”):service层 业务层
                 @Controller (“名称”):web层 控制层
                 @Autowired    做bean的注入时使用, 自动根据类型注入,如果按名称注入则需要与@Aualifier配合使用
                  @Inject    用法同@Autowired, 如果按名称注入则需要与 @Name 配合使用
                 @Qualifier (“名称”):指定自动注入的id名称
  • @Resource  做bean的注入时使用, @Resource的作用相当于@Autowired, 默认按照 byName 自动注入
  • @Bean  导入第三方包里面的注解
  • @Import 要导入到IOC容器里的组件
  • @JsonIgnore  在json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都会受影响。可标注在属性和方法上,如果注解失败,可能使用的是fastJson,尝试使用对应的注解来忽略字段。最好标注于属性上
  • @JsonIgnoreProperties 标注于类上,作用同上,可以多个属性。@JsonIgnoreProperties({"name"},{"age"})
  • @JsonFormat 标注于属性上,方便的把Date类型转换成我们想要的格式
  • @JsonSerialize 标注于属性或者getter上,用于在序列化时嵌入我们自定义代码,比如序列化double时在其后面限制两位小数
  • @JsonDeserialize 标注于属性或者setter上,用于在反序列化时嵌入我们自定义代码,类似上面
  • @JsonProperty 标注于属性上,指定某个属性和 json映射的名称
  • @ PostConstruct
                     自定义初始化,类执行顺序:1.构造方法 Constructor ,2. @Autowired,3.  @PostConstruct,一个类中只能有一个初始化方法
                      使用方式:
                    方式一:@PostConstruct
                                    public void init1(){
                                            //some init method
                                    }
                    方式二: public @PostConstruct void init2(){
                                        //some init method
                                   }
                    示例:
                       @RestController
                    @RequestMapping("/user")
                    public class UserController {
                            @Autowired
                            private UserService userService;
                        @GetMapping("/list")
                         public List list(){
                                return userService.list();
                           }
                           /*
                            初始化方法
                         */
                        @PostConstruct
                        public void init(){
                            userService.initUserSate();
                        }
                    }
                 除了采用注解完成初始化,也可以通过实现InitializingBean完成类的初始化
                 @RestController
                @RequestMapping("/log")
                public class LogController implements InitializingBean {
                    @Autowired
                    private UserService userService;
                    @Override
                    public void afterPropertiesSet() throws Exception {
                        userService.initUserSate();
                    }
                }
  • @ PreDestroy 
                     自定义销毁, 被@PreDestroy修饰的方法会在服务器卸载Servlet的时候运行,并且只会被服务器调用一次,类似于Servlet的destroy()方法。被@PreDestroy修饰的方法会在destroy()方法之后运行,在Servlet被彻底卸载之前
  • @Data   使用在类上,自动生成get、set、toString、equals、hashcode这些方法,不需要再写这些方法。@Data相当于@Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode这5个注解的合集。
  • @NoArgsConstructor  使用在类上,提供无参构造函数
  • @AllArgsConstructor 使用在类上,提供全参构造函数
  • @Builder
            创建者模式,就是一步一步创建对象,屏蔽了用户对内部构建的细节,精细的控制对象的构建过程,建议与 @AllArgsConstructor 和 @NoArgsConstructor配合使用,不然结合mybatis序列化时会出问题
             @Data
            @Builder
             @NoArgsConstructor
             @AllArgsConstructor 
            public class User {
                private int id;
                private String userName;
                private int state;
                private String phone;
                private String email;
            }
            使用: User user = User.builder()
                                                    .userName("zhouling")
                                                    .phone("13712345678")
                                                    .build();
  • @Singular
            配合@Builder使用,使用于集合字段(如果未设置value属性值,则集合字段需使用复数形式)
            提供两个方法,一个向集合添加单个元素 (方法名:集合字段名的单数形式 / value 属性值),一个 将另一个集合中 所有元素添加到集合中(方法名:集合字段名),还生成clear方法(方法名:clear+集合字段名)
  • @Transactional  该注解用于事务管理。当标注于类上,则表示类中所有方法都进行事务管理。当类中某个方法不需要进行事务管理,则在该方法前标注 @Transactional(propagation = Propagation.NOT_SUPPORTED)。  @Transactional(rollbackFor=Exception.class) //指定回滚,遇到异常Exception时回滚。 @Transactional(noRollbackFor=Exception.class)//指定不回滚,遇到运行期例外(throw new RuntimeException("注释");)会回滚。 @Transactional 注解应该只被应用到 public 可见度的方法上。 如果在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解,它也不会报错, 但是这个被注解的方法将不会展示已配置的事务设置。
  • @Scope springIOC容器作用域,在SpringIOC容器中用来配置bean实例的作用域对象。@Scope作用域包含如下几种:singleton(单实例模式,默认,全局有且只有一个实例)、prototype(多实例模式,每次获取bean的时候会有一个新的实例)、request(同一次请求,每次请求生成一个实例,该实例仅在该请求有效)、session(同一个会话级别,每次请求生成一个实例,)
  • @Value 获取配置文件中属性值,常用方式@Value("${   property : default_value}"),@Value("#{ obj.property? :default_value}"),区别:${}注入的是配置文件里的属性值,#{}注入的是 bean属性,系统属性,表达式。
  • @Profile  指定组件在哪个环境下才注入IOC容器,不指定,任何环境下都注入
  • @EnableAsync  使spring启用异步方法执行,标注于启动类上。 通过向Spring引入后置处理器AsyncAnnotationBeanPostProcessor,在bean的创建过程中对bean进行advisor增强,对@Async标识的bean增强异步功能
  • @Async  方法异步注解,标注于方法上,需要配合@ EnableAsync使用
  • @EnableScheduling 标注于启动类或者配置类上,表示开启定时任务扫描
  • @Scheduled 标注于定时任务类的方法上,定时任务类需标注@Component或@Service等组件注入注解
                package com.test.demo.config;
                import org.springframework.context.annotation.ComponentScan;
                import org.springframework.context.annotation.Configuration;
                import org.springframework.scheduling.annotation.EnableScheduling;
                @Configuration
                @ComponentScan({"com.test.demo.schedul"})
                @EnableScheduling
                public class AopConfig {}
                package com.test.demo.schedul;
                import org.springframework.scheduling.annotation.Scheduled;
                import org.springframework.stereotype.Service;
                import java.text.SimpleDateFormat;
                import java.util.Date;
                @Service
                public class SchedulService {
                        private static final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                          /**
                               * fixedRate和fixedRateString表示一个固定频率执行,上个任务开始后,多长时间后开始执行                                * initialDelay 和initialDelayString表⽰⼀个初始延迟时间,第⼀次被调⽤前延迟的时间
                               * 初始延迟1秒,每隔2秒执行
                           */
                          @Scheduled(fixedRate = 2000, initialDelay = 1000)
                          public void testFixedRate() {
                          System.out.println("fixedRate 当前时间:"+sdf.format(new Date()));
                          }
                            /**
                             * fixedDelay和fixedDelayString表示一个固定延迟时间执行,上一个任务完成后,延迟多长时间开始执行
                             * 每次执行完延迟2秒执行
                            */
                            @Scheduled(fixedDelay = 2000)
                            public void testFixedDelay(){
                                System.out.println("fixedDelay 当前时间:"+sdf.format(new Date()));
                            }
                              /**
                               * 根据cron表达式定时执行
                               * 每隔5分钟执⾏⼀次
                           */
                          @Scheduled(cron = "0 0/5 * * * ?")
                           public void testCron() {
                              System.out.println("cron 当前时间:"+sdf.format(new Date()));
                          }
                    }
                    package com.test.demo.testAnnotation;
                    import com.test.demo.config.AopConfig;
                    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
                    public class TestSchedul {
                          public static void main(String[] args) {
                              AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
                          }
                    }
  • @Enable***注解说明
                @EnableAspectAutoProxy:开启对AspectJ自动代理的支持;
                @EnableAsync:开启异步方法的支持;
                @EnableScheduling:开启计划任务的支持;
                @EnableWebMvc:开启web MVC的配置支持;
                @EnableConfigurationProperties:使@ConfigurationProperties注解的类生效;
                @EnableJpaRepositories:开启对SpringData JPA Repository的支持;
                @EnableTransactionManagement:开启注解式事务的支持,等同于xml配置⽂件中的 <tx:annotation-driven />,标注于启动类 ;
                @EnableCaching:开启注解式的缓存支持,标注于启动类或者配置类
                        @Cacheable  指定一个或多个Cache名字,同属性cacheNames,标注于方法上
                         @CacheEvict  仅清除缓存, 标注于方法上 与 @Scheduled 注解同时使用时可达到定时清除缓存
                        @CachePut  仅存放缓存
                         @Caching   用于在一个方法或者类上同时指定多个Spring Cache相关的注解
                        @CacheConfig  用于在同一个类中共享一些基础的cache配置,标注于类上,该操作会被覆盖
  • @ ContextConfiguration  注解通常与@RunWith(SpringJUnit4ClassRunner.class)联合使用用来测试
  • @ EqualsAndHashCode   任意类的定义都可以添加 @EqualsAndHashCode 注解,让lombok帮你生成 equals(Object other) hashCode() 方法的实现
  • @SuppressWarnings 告诉编译器忽略指定的告警,不用在编译完成后出现告警信息。可标注于类、构造器、方法、字段、局部变量上。
                    @SuppressWarnings("all")忽略所有告警
                 @SuppressWarnings(“unchecked”)忽略 unchecked告警信息,如使用List、ArrayList等未进行参数化产生的告警信息
                    @SuppressWarnings(“serial”)解决 The serializable class WmailCalendar does not declare a static final serialVersionUID field of type long告警
                     @SuppressWarnings(“deprecation”) 
                     @SuppressWarnings(“unchecked”, “deprecation”)等同于   @SuppressWarnings(value={“unchecked”, “deprecation”}) 同时忽略这两种告警
  • @Accessors
  • @Controller 标注在类上,使用它标记的类就是一个SpringMVC的 Controller类,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了 @RequestMapping 注解。 @Controller只是定义了一个控制器类,而使用 @RequestMapping 注解的方法才是处理请求的处理器
  • @RequestMapping 用户映射url请求,包括访问路径和参数,标注于类、方法上。除了指定url地址映射,还可指定请求方法(method)、请求参数(params)、请求头(headers)
                    请求方法有:get,post,delete,put
                    params和headers支持简单的表达式,
                    支持ant风格url路径,?匹配路径中一个字符,*匹配路径中任意多个字符,**匹配多层路径
                    URL中的{xxx}占位符可以通过 @PathVariable(“xxx”) 绑定到操作方法的入参中
  • @ResponseBody 将请求返回值放在response内,而不是页面 
  • @RequestBody 获取请求体中参数,常用于post请求
  • @PathVariable 用于接受路径参数
  • @RestController 该注解是@Controller和@ResponseBody的组合,标注在类上,表示该类中所有请求方法都默认加上@ResponseBody
  • @ControllerAdvice 
                全局异常处理  只需要定义类,添加该注解即可定义。可以在类中定义多个方法,不同方法处理不同异常@ExceptionHandler注解用来指明异常的类型
                全局数据绑定 用来做一些数据的初始化操作,在@ControllerAdvice标注的类中定义一些公共数据(需与@ModelAttribute注解接口,该接口标注于方法上),这样在每个Controller的接口中都可获取这些数据(通过Mode获取)
                全局数据预处理 需与@InitBinder注解结合使用,标注于方法上

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值