admin管理员组

文章数量:1794759

SpringBoot常用注解篇

SpringBoot常用注解篇

文章目录
  • 1.概述
  • 2.声明Bean的注解
  • 3.@Component注解
  • 4.@Service注解
    • 4.1 @service注解使用
    • 4.2 @Scope注解
    • 4.3 @Service和@Scope注解一起使用
  • 5.@Repository注解
  • 6.@Controller注解
  • 7.@RequestMapping注解
    • 7.2 method参数
    • 7.3 consumes参数
  • 参考文章

1.概述

Spring Boot简化了Spring应用的开发,使用注解去替代繁琐的XML配置。

Spring Boot中提供的许多注解:

  • @Component
  • @Service
  • @Scope
  • @Repository
  • @Controller
  • @RestController
  • @RequestMapping
  • @PathVariable
  • @ResponseBody
2.声明Bean的注解

如何吸引Spring容器的注意而“有幸”成为Spring 容器管理的Bean呢? 在Spring Boot中就依靠注解,Spring提供了多个注解来声明Bean为Spring容器管理的Bean,注解不同代表的含义不同,但是对Spring容器来说都是Spring管理的Bean

声明Bean的注解有:

  • @Component 没有明确角色的组件
  • @Service 在业务逻辑层(Service层)使用
  • @Repositpry 在数据访问层(dao层)使用
  • @Controller 用于标注控制层组件
  • @RestController
3.@Component注解

@Component源码

package org.springframework.stereotype; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @since 2.5 * @see Repository * @see Service * @see Controller * @see org.springframework.context.annotation.ClassPathBeanDefinitionScanner // 扫描包中Bean,注册 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Indexed public @interface Component { // 如果有返回组件名称,否则返回空字符串 String value() default ""; }

Component作用如下:

  • @Component作用在类上
  • @Component注解作用域默认为singleton
  • 使用注解配置和类路径扫描时,被@Component注解标注的类会被Spring扫描并注册为Bean
  • @Component使用在不确定哪一个层的时候使用,可以作用在任何层次,把普通pojo实例化到spring容器
  • 不推荐使用@Component注解,而应该使用它的扩展,如@Service、- @Repository

@Component 注解的例子: IUser.java

package com.example.demo.test; public interface IUser { public String get(); }

UserImpl.java

package com.example.demo.test.impl; import com.example.demo.test.IUser; import org.springframework.stereotype.Component; @Component public class UserImpl implements IUser { private String name = "UserImpl"; @Override public String get() { return name; } }

UserImplWithParam.java

package com.example.demo.test.impl; import com.example.demo.test.IUser; import org.springframework.stereotype.Component; @Component(value="UserWithParam") public class UserImplWithParam implements IUser { private String name = "UserComponentImplWithParam"; @Override public String get() { return name; } }

在DemoApplication.java中添加测试代码

DemoApplication.java

package com.example.demo; import com.example.demo.test.IUser; import com.example.demo.test.impl.UserImpl; import com.example.demo.test.impl.UserImplWithParam; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args); IUser userImpl = (UserImpl)context.getBean("userImpl"); System.out.println(userImpl.get()); IUser userWithParam = (UserImplWithParam)context.getBean("UserWithParam"); System.out.println(userWithParam.get()); } }

测试结果如下:

4.@Service注解

@service注解源码

package org.springframework.stereotype; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; /** * @since 2.5 * @see Component * @see Repository */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Service { @AliasFor(annotation = Component.class) String value() default ""; }

@Service的作用:

  • @Service是@Component注解的一个特例,作用在类上
  • @Service注解作用域默认为singleton
  • 使用注解配置和类路径扫描时,被@Service注解标注的类会被Spring扫描并注册为Bean
  • @Service用于标注业务层组件,表示定义一个bean
  • @Service使用时没有传参数,Bean名称默认为当前类的类名,首字母小写
  • @Service(“serviceBeanId”)或@Service(value=”serviceBeanId”)使用时传参数,使用value作为Bean名字
4.1 @service注解使用

@service 项目结构 IUser.java

package com.example.demo.test; public interface IUser { public String get(); }

UserSerciceImpl.java

package com.example.demo.test.impl; import com.example.demo.test.IUser; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements IUser { private String name = "UserImpl"; @Override public String get() { return name; } }

UserServiceImplWithParam.java

package com.example.demo.test.impl; import com.example.demo.test.IUser; import org.springframework.stereotype.Service; @Service(value="UserServiceWithParam") public class UserServiceImplWithParam implements IUser { private String name = "UserComponentImplWithParam"; @Override public String get() { return name; } }

最后在主程序中测试代码: demoApplication.java

package com.example.demo; import com.example.demo.test.IUser; import com.example.demo.test.impl.UserServiceImpl; import com.example.demo.test.impl.UserServiceImplWithParam; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args); IUser userImpl = (UserServiceImpl)context.getBean("userServiceImpl"); System.out.println(userImpl.get()); IUser userWithParam = (UserServiceImplWithParam)context.getBean("UserServiceWithParam"); System.out.println(userWithParam.get()); } }

测试结果如下:

4.2 @Scope注解

@Scope注解源码:

package org.springframework.context.annotation; /** 1. @since 2.5 2. @see org.springframework.stereotype.Component 3. @see org.springframework.context.annotation.Bean */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Scope { @AliasFor("scopeName") String value() default ""; @AliasFor("value") String scopeName() default ""; ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT; } @Scope有5中取值: 基本作用域: org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_SINGLETON = "singleton" org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE = "prototype" Web作用域: org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST = "request" org.springframework.web.context.WebApplicationContext#SCOPE_SESSION = "session" org.springframework.web.context.WebApplicationContext#SCOPE_APPLICATION = "application"

@Scope作用在类上和方法上 @Scope用来配置 spring bean 的作用域,它标识 bean 的作用域 singleton单例模式 Spring 容器中有且只有一个Bean实例,只要Spring容器不销毁或退出,该Bean实例就会一直存活

prototype原型模式 每次获取Bean的时候会有一个新的实例,Spring容器不能对返回Bean实例的整个生命周期负责

request模式 request只适用于Web程序,每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP request内有效,当请求结束后,该对象的生命周期即告结束

session模式 session只适用于Web程序,session作用域表示该针对每一次HTTP请求都会产生一个新的bean,同时该bean仅在当前HTTP session内有效

application模式 application只适用于Web程序,全局作用域

4.3 @Service和@Scope注解一起使用

@Scope的目录结构 IUser.java

package com.example.demo.test; public interface IUser { public String get(); }

SingleUserServiceImpl.java

package com.example.demo.test.impl; import com.example.demo.test.IUser; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; @Service @Scope("singleton") public class SingleUserServiceImpl implements IUser { private String name = "singleton"; @Override public String get() { return name; } }

PrototypeUserServiceImpl.java

package com.example.demo.test.impl; import com.example.demo.test.IUser; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; @Service @Scope("prototype") public class PrototypeUserServiceImpl implements IUser { private String name = "prototype"; @Override public String get() { return name; } }

在main函数中添加测试代码

package com.example.demo; import com.example.demo.test.IUser; import com.example.demo.test.impl.SingleUserServiceImpl; import com.example.demo.test.impl.PrototypeUserServiceImpl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args); SingleUserServiceImpl singleUserService1 = (SingleUserServiceImpl) context.getBean("singleUserServiceImpl"); SingleUserServiceImpl singleUserService2 = (SingleUserServiceImpl) context.getBean("singleUserServiceImpl"); System.out.println("singleton单例模式:" + singleUserService1.equals(singleUserService1)); PrototypeUserServiceImpl prototypeUserService1 = (PrototypeUserServiceImpl) context.getBean("prototypeUserServiceImpl"); PrototypeUserServiceImpl prototypeUserService2 = (PrototypeUserServiceImpl) context.getBean("prototypeUserServiceImpl"); System.out.println("prototype单例模式:" + prototypeUserService1.equals(prototypeUserService2)); } }

测试结果如下:

5.@Repository注解

@Repository注解源码:

package org.springframework.stereotype; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; /** * @since 2.0 * @see Component * @see Service * @see org.springframework.dao.DataAccessException * @see org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Repository { @AliasFor(annotation = Component.class) String value() default ""; }

@Repository注解作用在类上 @Repository注解作用域默认为singleton 使用注解配置和类路径扫描时,被@Reposito注解标注的类会被Spring扫描并注册为Bean @Repository注解用于标注数据访问组件,即DAO组件 @Repository注解的作用不只是将类识别为Bean,同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型

6.@Controller注解

@Controller注解源码:

package org.springframework.stereotype; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; /** * @since 2.5 * @see Component * @see org.springframework.web.bind.annotation.RequestMapping * @see org.springframework.context.annotation.ClassPathBeanDefinitionScanner */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Controller { @AliasFor(annotation = Component.class) String value() default ""; }

@Controller注解作用在类上 使用注解配置和类路径扫描时,被@Controller注解标注的类会被Spring扫描并注册为Bean @Controller用于标注Web中控制层组件 被@Controller标注的类负责处理由DispatcherServlet分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model返回给对应的View进行展示 @Controller和@RequestMapping、@RequestParam等一些注解共同处理URL的映射

7.@RequestMapping注解

@RequestMapping注解源码:

package org.springframework.web.bind.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.core.annotation.AliasFor; /** * @since 2.5 * @see GetMapping * @see PostMapping * @see PutMapping * @see DeleteMapping * @see PatchMapping * @see RequestParam * @see RequestAttribute * @see PathVariable * @see ModelAttribute * @see SessionAttribute * @see SessionAttributes * @see InitBinder * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter * @see org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerAdapter */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Mapping public @interface RequestMapping { String name() default ""; @AliasFor("path") String[] value() default {}; @AliasFor("value") String[] path() default {}; RequestMethod[] method() default {}; String[] params() default {}; String[] headers() default {}; String[] consumes() default {}; String[] produces() default {}; }

@RequestMapping注解作用在类或方法上 @RequestMapping注解用来处理请求地址映射 @RequestMapping注解有7个属性 7.1 value和path参数 指定请求的实际地址,指定的地址可以是URI Template 模式

使用示例:

@RequestMapping("/test") @RequestMapping(value="/test") @RequestMapping(path="/test") @RequestMapping(path="/test/*.do") 7.2 method参数

指定请求的method类型,请求类型:

package org.springframework.web.bind.annotation public enum RequestMethod { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE }

Spring Boot也提供了简化版后的@RequestMapping

@GetMapping @PostMapping @PutMapping @DeleteMapping @PatchMapping 使用示例: @RequestMapping(value="/test", method=RequestMethod.GET) @RequestMapping(value="/test", method=RequestMethod.POST) @GetMapping("/test") @PostMapping("/test") 7.3 consumes参数

指定处理允许的媒体类型,例如application/json, text/html

类型参考值见:org.springframework.http.MediaType

// 仅处理request Content-Type为“text/plain”类型的请求 @RequestMapping(value="/test", consumes=“text/plain”) @RequestMapping(value="/test", consumes={“text/plain”, “application/*”})

参考文章

blog.csdn/lipinganq/article/details/79155072?share_token=3e9f2a14-cf00-4c00-a92f-419aafa4b457 segmentfault/a/1190000022521844

本文标签: 注解常用SpringBoot