163 SpringBoot常用註解大全

 

轉自:https://mp.weixin.qq.com/s/PzZ31ju32-5epXpQeTZsNA

備份文件路徑:

 

1.整體圖

 

 

 

 

2.具體講解

 

平時使用SpringBoot開發項目,少不了要使用到它的註解。這些註解讓我們擺脫了繁瑣的傳統Spring XML配置,讓我們開發項目更加高效,今天我們就來聊聊SpringBoot中常用的註解!

常用註解概覽

這裏整理了一張SpringBoot常用註解的思維導圖,本文主要講解這些註解的用法。

組件相關注解

@Controller

用於修飾MVC中controller層的組件,SpringBoot中的組件掃描功能會識別到該註解,併爲修飾的類實例化對象,通常與@RequestMapping聯用,當SpringMVC獲取到請求時會轉發到指定路徑的方法進行處理。

/**
 * @auther macrozheng
 * @description 後臺用戶管理Controller
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Controller
@RequestMapping("/admin")
public class UmsAdminController {
    
}

@Service

用於修飾service層的組件,service層組件專注於系統業務邏輯的處理,同樣會被組件掃描並生成實例化對象。

/**
 * @auther macrozheng
 * @description 後臺用戶管理Service實現類
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Service
public class UmsAdminServiceImpl implements UmsAdminService {
    
}

@Repository

用於修飾dao層的組件,dao層組件專注於系統數據的處理,例如數據庫中的數據,同樣會被組件掃描並生成實例化對象。

/**
 * @auther macrozheng
 * @description 後臺用戶與角色關係管理自定義Dao
 * @date 2018/10/8
 * @github https://github.com/macrozheng
 */
@Repository
public interface UmsAdminRoleRelationDao {
    
}

@Component

用於修飾SpringBoot中的組件,會被組件掃描並生成實例化對象。@Controller@Service@Repository都是特殊的組件註解。

/**
 * @auther macrozheng
 * @description 取消訂單消息的生產者組件
 * @date 2018/9/14
 * @github https://github.com/macrozheng
 */
@Component
public class CancelOrderSender {
    
}

依賴注入註解

@Autowired

會根據對象的類型自動注入依賴對象,默認要求注入對象實例必須存在,可以配置required=false來注入不一定存在的對象。

/**
 * @auther macrozheng
 * @description 後臺用戶管理Controller
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Controller
@RequestMapping("/admin")
public class UmsAdminController {
    @Autowired
    private UmsAdminService adminService;
}

@Resource

默認會根據對象的名稱自動注入依賴對象,如果想要根據類型進行注入,可以設置屬性爲type = UmsAdminService.class

/**
 * @auther macrozheng
 * @description 後臺用戶管理Controller
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Controller
@RequestMapping("/admin")
public class UmsAdminController {
    @Autowired
    @Resource(name = "umsAdminServiceImpl")
    private UmsAdminService adminService;
}

@Qualifier

當同一個對象有多個實例可以注入時,使用@Autowired註解無法進行注入,這時可以使用@Qualifier註解指定實例的名稱進行精確注入。

/**
 * @auther macrozheng
 * @description 後臺用戶管理Controller
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Controller
@RequestMapping("/admin")
public class UmsAdminController {
    @Autowired
    @Qualifier("umsAdminServiceImpl")
    private UmsAdminService adminService;
}

實例與生命週期相關注解

@Bean

用於修飾方法,標識該方法會創建一個Bean實例,並交給Spring容器來管理。

/**
 * @auther macrozheng
 * @description RestTemplate相關配置
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

@Scope

用於聲明一個SpringBean實例的作用域,作用域的範圍有以下幾種:

  • singleton:單例模式,在Spring容器中該實例唯一,Spring默認的實例模式。

  • prototype:原型模式,每次使用實例都將重新創建。

  • request:在同一請求中使用相同的實例,不同請求重新創建。

  • session:在同一會話中使用相同的實例,不同會話重新創建。

/**
 * @auther macrozheng
 * @description RestTemplate相關配置
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Configuration
public class RestTemplateConfig {
    @Bean
    @Scope("singleton")
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

@Primary

當同一個對象有多個實例時,優先選擇該實例。

/**
 * @auther macrozheng
 * @description Jackson相關配置,配置json不返回null的字段
 * @date 2018/8/2
 * @github https://github.com/macrozheng
 */
@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder{
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }
}

@PostConstruct

用於修飾方法,當對象實例被創建並且依賴注入完成後執行,可用於對象實例的初始化操作。

@PreDestroy

用於修飾方法,當對象實例將被Spring容器移除時執行,可用於對象實例持有資源的釋放。

@PostConstruct、@PreDestroy示例

/**
 * @auther macrozheng
 * @description 動態權限數據源,用於獲取動態權限規則
 * @date 2020/2/7
 * @github https://github.com/macrozheng
 */
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static Map<String, ConfigAttribute> configAttributeMap = null;
    @Autowired
    private DynamicSecurityService dynamicSecurityService;

    @PostConstruct
    public void loadDataSource() {
        configAttributeMap = dynamicSecurityService.loadDataSource();
    }

    @PostConstruct
    public void loadDataSource() {
        configAttributeMap = dynamicSecurityService.loadDataSource();
    }

    @PreDestroy
    public void clearDataSource() {
        configAttributeMap.clear();
        configAttributeMap = null;
    }
}

SpringMVC相關注解

@RequestMapping

可用於將Web請求路徑映射到處理類的方法上,當作用於類上時,可以統一類中所有方法的路由路徑,當作用於方法上時,可單獨指定方法的路由路徑。

method屬性可以指定請求的方式,如GET、POST、PUT、DELETE等。

@RequestBody

表示方法的請求參數爲JSON格式,從Body中傳入,將自動綁定到方法參數對象中。

@ResponseBody

表示方法將返回JSON格式的數據,會自動將返回的對象轉化爲JSON數據。

@RequestParam

用於接收請求參數,可以是如下三種形式:

  • query param:GET請求拼接在地址裏的參數。

  • form data:POST表單提交的參數。

  • multipart:文件上傳請求的部分參數。

@PathVariable

用於接收請求路徑中的參數,常用於REST風格的API。

@RequestPart

用於接收文件上傳中的文件參數,通常是multipart/form-data形式傳入的參數。

/**
 * @auther macrozheng
 * @description MinIO對象存儲管理Controller
 * @date 2019/12/25
 * @github https://github.com/macrozheng
 */
@Controller
@RequestMapping("/minio")
public class MinioController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult upload(@RequestPart("file") MultipartFile file) {
            //省略文件上傳操作...
            return CommonResult.success(minioUploadDto);
    }
}

SpringMVC註解示例

/**
 * @auther macrozheng
 * @description 後臺用戶管理Controller
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Controller
@RequestMapping("/admin")
public class UmsAdminController {

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<UmsAdmin> register(@RequestBody UmsAdminParam umsAdminParam) {
        UmsAdmin umsAdmin = adminService.register(umsAdminParam);
        if (umsAdmin == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(umsAdmin);
    }
    
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<UmsAdmin> adminList = adminService.list(keyword, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(adminList));
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<UmsAdmin> getItem(@PathVariable Long id) {
        UmsAdmin admin = adminService.getItem(id);
        return CommonResult.success(admin);
    }
}

@RestController

用於表示controller層的組件,與@Controller註解的不同在於,相當於在每個請求處理方法上都添加了@ResponseBody註解,這些方法都將返回JSON格式數據。

@GetMapping

用於表示GET請求方法,等價於@RequestMapping(method = RequestMethod.GET)

@PostMapping

用於表示POST請求方法,等價於@RequestMapping(method = RequestMethod.POST)

REST風格註解示例

/**
 * @auther macrozheng
 * @description 後臺用戶管理Controller
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@RestController
@RequestMapping("/admin")
public class UmsAdminController {

    @PostMapping("/register")
    public CommonResult<UmsAdmin> register(@RequestBody UmsAdminParam umsAdminParam) {
        UmsAdmin umsAdmin = adminService.register(umsAdminParam);
        if (umsAdmin == null) {
            return CommonResult.failed();
        }
        return CommonResult.success(umsAdmin);
    }

    @GetMapping("/list")
    public CommonResult<CommonPage<UmsAdmin>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                   @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        List<UmsAdmin> adminList = adminService.list(keyword, pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(adminList));
    }
}

配置相關注解

@Configuration

用於聲明一個Java形式的配置類,SpringBoot推薦使用Java配置,在該類中聲明的Bean等配置將被SpringBoot的組件掃描功能掃描到。

/**
 * @auther macrozheng
 * @description MyBatis相關配置
 * @date 2019/4/8
 * @github https://github.com/macrozheng
 */
@Configuration
@MapperScan({"com.macro.mall.mapper","com.macro.mall.dao"})
public class MyBatisConfig {
}

@EnableAutoConfiguration

啓用SpringBoot的自動化配置,會根據你在pom.xml添加的依賴和application-dev.yml中的配置自動創建你需要的配置。

@Configuration
@EnableAutoConfiguration
public class AppConfig {
}

@ComponentScan

啓用SpringBoot的組件掃描功能,將自動裝配和注入指定包下的Bean實例。

@Configuration
@ComponentScan({"xyz.erupt","com.macro.mall.tiny"})
public class EruptConfig {
}

@SpringBootApplication

用於表示SpringBoot應用中的啓動類,相當於@EnableAutoConfiguration@EnableAutoConfiguration@ComponentScan三個註解的結合體。

@SpringBootApplication
public class MallTinyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MallTinyApplication.classargs);
    }

}

@EnableCaching

當添加Spring Data Redis依賴之後,可用該註解開啓Spring基於註解的緩存管理功能。

/**
 * @auther macrozheng
 * @description Redis配置類
 * @date 2020/3/2
 * @github https://github.com/macrozheng
 */
@EnableCaching
@Configuration
public class RedisConfig extends BaseRedisConfig {

}

@value

用於注入在配置文件中配置好的屬性,例如我們可以在application.yml配置如下屬性:

jwt:
  tokenHeader: Authorization #JWT存儲的請求頭
  secret: mall-admin-secret #JWT加解密使用的密鑰
  expiration: 604800 #JWT的超期限時間(60*60*24*7)
  tokenHead: 'Bearer '  #JWT負載中拿到開頭

然後在Java類中就可以使用@Value注入並進行使用了。

public class JwtTokenUtil {
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
}

@ConfigurationProperties

用於批量注入外部配置,以對象的形式來導入指定前綴的配置,比如這裏我們在application.yml中指定了secure.ignored爲前綴的屬性:

secure:
  ignored:
    urls: #安全路徑白名單
      - /swagger-ui/
      - /swagger-resources/**
      - /**/v2/api-docs
      - /**/*.html
      - /**/*.js
      - /**/*.css
      - /**/*.png
      - /**/*.map
      - /favicon.ico
      - /actuator/**
      - /druid/**

然後在Java類中定義一個urls屬性就可以導入配置文件中的屬性了。

/**
 * @auther macrozheng
 * @description SpringSecurity白名單資源路徑配置
 * @date 2018/11/5
 * @github https://github.com/macrozheng
 */
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "secure.ignored")
public class IgnoreUrlsConfig {

    private List<String> urls = new ArrayList<>();

}

@Conditional

用於表示當某個條件滿足時,該組件或Bean將被Spring容器創建,下面是幾個常用的條件註解。

  • @ConditionalOnBean:當某個Bean存在時,配置生效。

  • @ConditionalOnMissingBean:當某個Bean不存在時,配置生效。

  • @ConditionalOnClass:當某個類在Classpath存在時,配置生效。

  • @ConditionalOnMissingClass:當某個類在Classpath不存在時,配置生效。

/**
 * @auther macrozheng
 * @description Jackson相關配置,配置json不返回null的字段
 * @date 2018/8/2
 * @github https://github.com/macrozheng
 */
@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder{
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }
}

數據庫事務相關注解

@EnableTransactionManagement

啓用Spring基於註解的事務管理功能,需要和@Configuration註解一起使用。

/**
 * @auther macrozheng
 * @description MyBatis相關配置
 * @date 2019/4/8
 * @github https://github.com/macrozheng
 */
@Configuration
@EnableTransactionManagement
@MapperScan({"com.macro.mall.mapper","com.macro.mall.dao"})
public class MyBatisConfig {
}

@Transactional

表示方法和類需要開啓事務,當作用與類上時,類中所有方法均會開啓事務,當作用於方法上時,方法開啓事務,方法上的註解無法被子類所繼承。

/**
 * @auther macrozheng
 * @description 前臺訂單管理Service
 * @date 2018/8/30
 * @github https://github.com/macrozheng
 */
public interface OmsPortalOrderService {

    /**
     * 根據提交信息生成訂單
     */
    @Transactional
    Map<String, Object> generateOrder(OrderParam orderParam);
}

SpringSecurity相關注解

@EnableWebSecurity

啓用SpringSecurity的Web功能。

@EnableGlobalMethodSecurity

啓用SpringSecurity基於方法的安全功能,當我們使用@PreAuthorize修飾接口方法時,需要有對應權限的用戶才能訪問。

SpringSecurity配置示例

/**
 * @auther macrozheng
 * @description SpringSecurity配置
 * @date 2019/10/8
 * @github https://github.com/macrozheng
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig{
    
}

全局異常處理註解

@ControllerAdvice

常與@ExceptionHandler註解一起使用,用於捕獲全局異常,能作用於所有controller中。

@ExceptionHandler

修飾方法時,表示該方法爲處理全局異常的方法。

全局異常處理示例

/**
 * @auther macrozheng
 * @description 全局異常處理
 * @date 2020/2/27
 * @github https://github.com/macrozheng
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public CommonResult handle(ApiException e{
        if (e.getErrorCode() != null) {
            return CommonResult.failed(e.getErrorCode());
        }
        return CommonResult.failed(e.getMessage());
    }
}

AOP相關注解

@Aspect

用於定義切面,切面是通知和切點的結合,定義了何時、何地應用通知功能。

@Before

表示前置通知(Before),通知方法會在目標方法調用之前執行,通知描述了切面要完成的工作以及何時執行。

@After

表示後置通知(After),通知方法會在目標方法返回或拋出異常後執行。

@AfterReturning

表示返回通知(AfterReturning),通知方法會在目標方法返回後執行。

@AfterThrowing

表示異常通知(AfterThrowing),通知方法會在目標方法返回後執行。

@Around

表示環繞通知(Around),通知方法會將目標方法封裝起來,在目標方法調用之前和之後執行自定義的行爲。

@Pointcut

定義切點表達式,定義了通知功能被應用的範圍。

@Order

用於定義組件的執行順序,在AOP中指的是切面的執行順序,value屬性越低優先級越高。

AOP相關示例

/**
 * @auther macrozheng
 * @description 統一日誌處理切面
 * @date 2018/4/26
 * @github https://github.com/macrozheng
 */
@Aspect
@Component
@Order(1)
public class WebLogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    @Pointcut("execution(public * com.macro.mall.tiny.controller.*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        WebLog webLog = new WebLog();
        //省略日誌處理操作...
        Object result = joinPoint.proceed();
        LOGGER.info("{}", JSONUtil.parse(webLog));
        return result;
    }
    
}

測試相關注解

@SpringBootTest

用於指定測試類啓用Spring Boot Test功能,默認會提供Mock環境。

@Test

指定方法爲測試方法。

測試示例

/**
 * @auther macrozheng
 * @description JUnit基本測試
 * @date 2022/10/11
 * @github https://github.com/macrozheng
 */
@SpringBootTest
public class FirstTest {
    @Test
    public void test() {
        int a=1;
        Assertions.assertEquals(1,a);
    }
}

總結

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章