Spring注解大全


一、Spring bean注解

1.1、@SpringBootApplication

申明讓spring boot自動給程序進行必要的配置,這個配置等同於:@Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三個配置。

1.2、@Component

泛指各種組件,就是說當我們的類不屬於各種歸類的時候(不屬於@Controller、@Services等的時候),我們就可以使用@Component來標注這個類,把普通pojo實例化到spring容器中,相當於配置文件中的:<bean id="" class=""/>。

所以可以理解為@Component可以細化為@Reposity,@Service,@Controller。

@Component("conversionImpl") //其實默認的spring中的Bean id 為 conversionImpl(首字母小寫) public class ConversionImpl implements Conversion { @Autowired private RedisClient redisClient; }

1.3、@ComponentScan

@ComponentScan主要就是定義掃描的路徑從中找出標識了需要裝配的類自動裝配到spring的bean容器中。前面說到過@Controller注解,@Service,@Repository注解,它們其實都是組件,屬於@Component注解,而@ComponentScan注解默認會裝配標識了@Controller,@Service,@Repository,@Component注解的類到spring容器中。

//掃描com.demo下的組件 @ComponentScan(value="com.demo") @Configuration public class myConfig { }

1.4、@Service

一般用於修飾service層的組件

@Service() public class UserService{ @Resource private UserDao userDao; public void add(){ userDao.add(); } }

1.5、@EnableAutoConfiguration

SpringBoot自動配置(auto-configuration):嘗試根據你添加的jar依賴自動配置你的Spring應用。例如,如果你的classpath下存在HSQLDB,並且你沒有手動配置任何數據庫連接beans,那么我們將自動配置一個內存型(in-memory)數據庫。你可以將@EnableAutoConfiguration或者@SpringBootApplication注解添加到一個@Configuration類上來選擇自動配置。如果發現應用了你不想要的特定自動配置類,你可以使用@EnableAutoConfiguration注解的排除屬性來禁用它們。

1.6、@Configuration

Spring3.0,相當於傳統的xml配置文件,如果有些第三方庫需要用到xml文件,建議仍然通過@Configuration類作為項目的配置主類可以使用@ImportResource注解加載xml配置文件。

proxyBeanMethods屬性默認值是true,也就是說該配置類會被代理(CGLIB),在同一個配置文件中調用其它被@Bean注解標注的方法獲取對象時會直接從IOC容器之中獲取。

注意:@Configuration注解的配置類有如下要求:

  1. @Configuration不可以是final類型;

  2. @Configuration不可以是匿名類;

  3. 嵌套的configuration必須是靜態類。

@Configuration public class AppConfig { // 未指定bean 的名稱,默認采用的是 "方法名" + "首字母小寫"的配置方式 @Bean public MyBean myBean(){ return new MyBean(); } }

1.7、@ConfigurationProperties

  • 前綴定義了哪些外部屬性將綁定到類的字段上

  • 根據 Spring Boot 寬松的綁定規則,類的屬性名稱必須與外部屬性的名稱匹配

  • 我們可以簡單地用一個值初始化一個字段來定義一個默認值

  • 類本身可以是包私有的

  • 類的字段必須有公共 setter 方法

激活 @ConfigurationProperties

  • 只有當類所在的包被 Spring @ComponentScan 注解掃描到才會生效,默認情況下,該注解會掃描在主應用類下的所有包結構。

可以通過添加 @Component 注解讓 Component Scan 掃描到。

@Component @ConfigurationProperties(prefix = "demo") class DemoProperties { }
  • 也可以通過 Spring 的 Java Configuration 特性實現同樣的效果。

@Configuration
class PropertiesConfig {
    @Bean
    public DemoProperties demoProperties(){
        return new DemoProperties();
    }
}
  • 使用 @EnableConfigurationProperties 注解讓我們的類被 Spring Boot 所知道,在該注解中其實是用了@Import(EnableConfigurationPropertiesImportSelector.class) 實現

@Configuration
@EnableConfigurationProperties(DemoProperties.class)
class PropertiesConfig {
}

Duration

Spring Boot 內置支持從配置參數中解析 durations (持續時間),官網文檔 給出了明確的說明。

配置 duration 不寫單位,默認按照毫秒來指定,我們也可已通過 @DurationUnit 來指定單位。常用單位如下:

  • ns for nanoseconds (納秒)

  • us for microseconds (微秒)

  • ms for milliseconds (毫秒)

  • s for seconds (秒)

  • m for minutes (分)

  • h for hours (時)

  • d for days (天)

@Data
@ConfigurationProperties(prefix = "demo")
class DemoProperties {
    @DurarionUnit(ChronoUnit.SECONDS)
    private Duration timeout;
}

DataSize

與 Duration 的用法一毛一樣,默認單位是 byte (字節),可以通過 @DataSizeUnit 單位指定

但是,我測試的時候打印出來結果都是以 B (bytes) 來顯示。常見單位如下

  • B for bytes

  • KB for kilobytes

  • MB for megabytes

  • GB for gigabytes

  • TB for terabytes

1.8、@Import

@Import注解是引入帶有@Configuration的java類。

@Configuration @Import({MyImportSelector.class, MyImportBeanDefinitionRegistrar.class, MyImportSelector1.class}) public static class Config { @Bean public BeanDemo0 beanDemo() { System.out.println("----beanDemo----"); BeanDemo0 beanDemo0 = new BeanDemo0(); beanDemo0.setId(1); beanDemo0.setName("123"); return beanDemo0; } }

1.9、@ImportResource

@ImportResource是引入spring配置文件.xml

@Configuration @ImportResource(locations = {"applicationContext.xml"}) public class BeanConfigTest { }

1.10、@Resource、@Autowired和@Inject

@Resource和@Autowired都是做bean注入時使用。

@Resource的作用相當於@Autowired,只不過@Autowired按照byType自動注入。

1、共同點

兩者都可以寫在字段和setter方法上。兩者如果都寫在字段上,那么就不需要再寫setter方法。

2、不同點

1.10.1、@Autowired

Spring 2.5 引入。@Autowired為Spring提供的注解,需要導入包org.springframework.beans.factory.annotation.Autowired,只按照byType注入。

@Autowired注解是按照類型(byType)裝配依賴對象,默認情況下它要求依賴對象必須存在,如果允許null值,可以設置它的required屬性為false。如果我們想使用按照名稱(byName)來裝配,可以結合@Qualifier注解一起使用。

public class TestServiceImpl { // 下面兩種@Autowired只要使用一種即可 @Autowired private UserDao userDao; // 用於字段上 @Autowired public void setUserDao(UserDao userDao) { // 用於屬性的方法上 this.userDao = userDao; } @Autowired @Qualifier("userDao") private UserDao userDao; }

1.10.2、@Resource

@Resource默認按照ByName自動注入,由J2EE提供,是JSR250規范的實現,需要導入javax.annotation實現注入。

@Resource有兩個重要的屬性:name和type,而Spring將@Resource注解的name屬性解析為bean的名字,而type屬性則解析為bean的類型。所以,如果使用name屬性,則使用byName的自動注入策略,而使用type屬性時則使用byType自動注入策略。如果既不制定name也不制定type屬性,這時將通過反射機制使用byName自動注入策略。

public class TestServiceImpl { // 下面兩種@Resource只要使用一種即可 @Resource(name="userDao") private UserDao userDao; // 用於字段上 @Resource(name="userDao") public void setUserDao(UserDao userDao) { // 用於屬性的setter方法上 this.userDao = userDao; } }

注:最好是將@Resource放在setter方法上,因為這樣更符合面向對象的思想,通過set、get去操作屬性,而不是直接去操作屬性。

@Resource裝配順序:

  • 如果同時指定了name和type,則從Spring上下文中找到唯一匹配的bean進行裝配,找不到則拋出異常。

  • 如果指定了name,則從上下文中查找名稱(id)匹配的bean進行裝配,找不到則拋出異常。

  • 如果指定了type,則從上下文中找到類似匹配的唯一bean進行裝配,找不到或是找到多個,都會拋出異常。

  • 如果既沒有指定name,又沒有指定type,則自動按照byName方式進行裝配;如果沒有匹配,則回退為一個原始類型進行匹配,如果匹配則自動裝配。

1.10.3、@Inject

@Inject是JSR330 (Dependency Injection for Java)中的規范,需要導入javax.inject.Inject;實現注入。@Inject可以作用在變量、setter方法、構造函數上。根據類型進行自動裝配的,如果需要按名稱進行裝配,則需要配合@Named。

@Named("XXX") 中的 XXX是 Bean 的名稱,所以 @Inject和 @Named結合使用時,自動注入的策略就從 byType 轉變成 byName 了。

public class User{ private Person person; @Inject pbulic void setPerson(Person person){ this.person = person; } @Inject pbulic void setPerson1(@Named("main")Person person) { this.person = person; } }

1.11、@Repository

用於注解dao層,在daoImpl類上面注解。

1.12、@Bean

產生一個Bean對象,然后這個Bean對象交給Spring管理。用@Bean標注方法等價於XML中配置的bean。

產生這個Bean對象的方法Spring只會調用一次,隨后這個Spring將會將這個Bean對象放在自己的IOC容器中。SpringIOC 容器管理一個或者多個bean,這些bean都需要在@Configuration注解下進行創建,在一個方法上使用@Bean注解就表明這個方法需要交給Spring進行管理。

@Bean public class UserTest(){ public User getUser(){ System.out.println("創建user實例"); return new User("張三",26); } }

@Bean 注解的屬性有:value、name、autowire、initMethod、destroyMethod。

name 和 value 兩個屬性是相同的含義的, 在代碼中定義了別名。為 bean 起一個名字,如果默認沒有寫該屬性,那么就使用方法的名稱為該 bean 的名稱。

autowire指定 bean 的裝配方式, 根據名稱 和 根據類型 裝配, 一般不設置,采用默認即可。autowire指定的裝配方式 有三種Autowire.NO (默認設置)、Autowire.BY_NAME、Autowire.BY_TYPE。

initMethod和destroyMethod指定bean的初始化方法和銷毀方法, 直接指定方法名稱即可,不用帶括號。

public class MyBean { public MyBean(){ System.out.println("MyBean Initializing"); } public void init(){ System.out.println("Bean 初始化方法被調用"); } public void destroy(){ System.out.println("Bean 銷毀方法被調用"); } } @Configuration public class AppConfig { @Bean(initMethod = "init", destroyMethod = "destroy") public MyBean myBean(){ return new MyBean(); } }

1.13、@Scope

@Scope注解默認的singleton單例模式。

@Scope注解是springIoc容器中的一個作用域,在 Spring IoC 容器中具有以下幾種作用域:基本作用域singleton(單例)、prototype(多例),Web 作用域(reqeust、session、globalsession),自定義作用域。

prototype原型模式:
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)在每次注入的時候回自動創建一個新的bean實例 singleton單例模式: @Scope(value=ConfigurableBeanFactory.SCOPE_SINGLETON)單例模式,在整個應用中只能創建一個實例 globalsession模式: @Scope(value=WebApplicationContext.SCOPE_GLOBAL_SESSION)全局session中的一般不常用 @Scope(value=WebApplicationContext.SCOPE_APPLICATION)在一個web應用中只創建一個實例 request模式: @Scope(value=WebApplicationContext.SCOPE_REQUEST)在一個請求中創建一個實例 session模式: @Scope(value=WebApplicationContext.SCOPE_SESSION)每次創建一個會話中創建一個實例
 
@Configuration public class myConfig { //默認是單例的。不需要特別說明 @Bean("person") public Person person(){ return new Person("binghe002", 18); } } @Configuration public class myConfig { //Person對象的作用域修改成prototype,多例的 @Scope("prototype") @Bean("person") public Person person(){ return new Person("binghe002", 18); } }

1.14、@Value

@Value的作用是通過注解將常量、配置文件中的值、其他bean的屬性值注入到變量中,作為變量的初始值。

(1)、普通注入

@Value("張三") private String name; // 注入普通字符串

(2)、bean屬性、系統屬性、表達式注入,使用@Value("#{}")。bean屬性注入需要注入者和被注入者屬於同一個IOC容器,或者父子IOC容器關系,在同一個作用域內。

// 注入其他Bean屬性:注入beanInject對象的屬性another,類具體定義見下面 @Value("#{beanInject.another}") private String fromAnotherBean; // 注入操作系統屬性 @Value("#{systemProperties['os.name']}") private String systemPropertiesName; //注入表達式結果 @Value("#{T(java.lang.Math).random() * 100.0 }") private double randomNumber;

(3)、配置文件屬性注入@Value("${}")

@Value("#{}")讀取配置文件中的值,注入到變量中去。配置文件分為默認配置文件application.properties和自定義配置文件。

1.15、@RestController

Spring4,注解是@Controller和@ResponseBody的合集,表示這是個控制器bean,並且是將函數的返回值直 接填入HTTP響應體中,是REST風格的控制器。

@RestController @RequestMapping(“/demoInfo2”) publicclass DemoController2 { @RequestMapping("/test") public String test(){ return "ok"; } }

1.16、@Controller

在SpringMVC 中,控制器Controller 負責處理由DispatcherServlet 分發的請求,它把用戶請求的數據經過業務處理層處理之后封裝成一個Model ,然后再把該Model 返回給對應的View 進行展示。在SpringMVC 中提供了一個非常簡便的定義Controller 的方法,你無需繼承特定的類或實現特定的接口,只需使用@Controller 標記一個類是Controller ,然后使用@RequestMapping 和@RequestParam 等一些注解用以定義URL 請求和Controller 方法之間的映射,這樣的Controller 就能被外界訪問到。此外Controller 不會直接依賴於HttpServletRequest 和HttpServletResponse 等HttpServlet 對象,它們可以通過Controller 的方法參數靈活的獲取到。

用於定義控制器類,在spring 項目中由控制器負責將用戶發來的URL請求轉發到對應的服務接口(service層),一般這個注解在類中,通常方法需要配合注解@RequestMapping。示例代碼:

@Controller @RequestMapping(“/demoInfo”) public class DemoController { @Autowired private DemoInfoService demoInfoService; @RequestMapping("/hello") public String hello(Map<String,Object> map){ System.out.println("DemoController.hello()"); map.put("hello","from TemplateController.helloHtml"); //會使用hello.html或者hello.ftl模板進行渲染顯示. return"/hello"; } }

1.17、@RequestMapping

提供路由信息,是一個用來處理請求地址映射的注解,可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。

RequestMapping注解有六個屬性,下面我們把她分成三類進行說明(下面有相應示例)。

1、 value, method;

value:     指定請求的實際地址,指定的地址可以是URI Template 模式(后面將會說明);

method:  指定請求的method類型, GET、POST、PUT、DELETE等;

2、consumes,produces

consumes: 指定處理請求的提交內容類型(Content-Type),例如application/json, text/html;

produces:    指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回;

3、params,headers

params: 指定request中必須包含某些參數值是,才讓該方法處理。

headers: 指定request中必須包含某些指定的header值,才能讓該方法處理請求。

@RestController @RequestMapping("/home") public class IndexController { /** * 將多個請求映射到一個方法上去 */ @RequestMapping(value = { “”, “/page”, "page*”, "view/*,**/msg" }) String indexMultipleMapping() { return "Hello from index multiple mapping.”; } /** * 是否是必須傳參 * /home/name?person=xyz 或 /home/name */ @RequestMapping(value = “/name”) String getName(@RequestParam(value = "person”, required = false) String personName) { return "Required element of request param”; } /** * 請求類型,請求參數,默認值 */ @RequestMapping(value = "/name", method = RequestMethod.GET) String getName(@RequestParam(value = "person", defaultValue = "John") String personName) { return "Required element of request param"; } /** * 產生一個 JSON 響應 */ @RequestMapping(value = "/prod", produces = { "application/JSON" }) @ResponseBody String getProduces() { return "Produces attribute"; } /** * 可以同時處理請求中的 JSON 和 XML 內容 */ @RequestMapping(value = "/cons", consumes = { "application/JSON", "application/XML" }) String getConsumes() { return "Consumes attribute"; } /** * 根據請求中的消息頭內容縮小請求映射的范圍 */ @RequestMapping(value = “/head”, headers = { "content-type=text/plain”, "content-type=text/html" }) String post() { return "Mapping applied along with headers”; } /** * 可以讓多個處理方法處理到同一個URL 的請求, 而這些請求的參數是不一樣的 */ @RequestMapping(value = “/fetch”, params = { "personId=10" }) String getParams(@RequestParam(“personId”) String id) { return "Fetched parameter using params attribute = " + id; } /** * 使用正則表達式來只處理可以匹配到正則表達式的動態 URI */ @RequestMapping(value = “/fetch/{id:[a-z]+}/{name}”, method = RequestMethod.GET) String getDynamicUriValueRegex(@PathVariable(“name”) String name) { System.out.println(“Name is " + name); return "Dynamic URI parameter fetched using regex”; } /** * 向 /home 發起的一個請求將會由 default() 來處理,因為注解並沒有指定任何值 */ @RequestMapping() String default () { return "This is a default method for the class”; } }

1.18、@ModelAttribute和 @SessionAttributes

該Controller的所有方法在調用前,先執行此@ModelAttribute方法,可用於注解和方法參數中,可以把這個@ModelAttribute特性,應用在BaseController當中,所有的Controller繼承BaseController,即可實現在調用Controller時,先執行@ModelAttribute方法。

1.18.1、@SessionAttributes

@SessionAttributes即將值放到session作用域中,寫在class上面。

具體示例參見下面:使用 @ModelAttribute 和 @SessionAttributes 傳遞和保存數據SpringMVC 支持使用 @ModelAttribute 和 @SessionAttributes 在不同的模型(model)和控制器之間共享數據。 @ModelAttribute 主要有兩種使用方式,一種是標注在方法上,一種是標注在 Controller 方法參數上。

1.18.2、@ModelAttribute

當 @ModelAttribute 標記在方法上的時候,該方法將在處理器方法執行之前執行,然后把返回的對象存放在 session 或模型屬性中,屬性名稱可以使用 @ModelAttribute(“attributeName”) 在標記方法的時候指定,若未指定,則使用返回類型的類名稱(首字母小寫)作為屬性名稱。

1.19、@PathVariable

用於將請求URL中的模板變量映射到功能處理方法的參數上,即取出uri模板中的變量作為參數。如:

@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"; } @RequestMapping(value="/product/{productId}",method = RequestMethod.GET) public String getProduct(@PathVariable("productId") String productId){ System.out.println("Product Id : " + productId); return "hello"; } @RequestMapping(value="/javabeat/{regexp1:[a-z-]+}", method = RequestMethod.GET) public String getRegExp(@PathVariable("regexp1") String regexp1){ System.out.println("URI Part 1 : " + regexp1); return "hello"; } }

1.20、@RequestParam

@RequestParam主要用於在SpringMVC后台控制層獲取參數,類似一種是request.getParameter("name"),它有三個常用參數:defaultValue = "0", required = false, value = "isApp";defaultValue 表示設置默認值,required 通過boolean設置是否是必須要傳入的參數,value 值表示接受的傳入的參數類型。

public Resp test(@RequestParam(value="course_id") Integer id){ return Resp.success(customerInfoService.fetch(id)); }

1.21、@ResponseBody

Spring4后出現的注解。

作用: 該注解用於將Controller的方法返回的對象,用於構建RESTful的api,通過適當的HttpMessageConverter轉換為指定格式后,寫入到Response對象的body數據區。

使用時機:返回的數據不是html標簽的頁面,而是其他某種格式的數據時(如json、xml等)使用。

@RequestMapping(“/test”) @ResponseBody public String test(){ return”ok”; }

二、切面(AOP)相關注解

在運行時,動態地將代碼切入到類的指定方法、指定位置上的編程思想就是面向切面的編程,簡稱AOP(aspect object programming)。AOP編程,可以將一些系統性相關的編程工作,獨立提取出來,獨立實現,然后通過切面切入進系統。從而避免了在業務邏輯的代碼中混入很多的系統相關的邏輯——比如權限管理,事物管理,日志記錄等等。這些系統性的編程工作都可以獨立編碼實現,然后通過AOP技術切入進系統即可。從而達到了 將不同的關注點分離出來的效果。

aop技術的功能是讓關注點與業務邏輯代碼進行分離;而重復的代碼就是關注點;關注點形成的類,就是切面(類)

Spring支持AspectJ的注解式aop編程,需要在java的配置類中使用@EnableAspectJAutoProxy注解開啟Spring對AspectJ代理的支持。下面介紹下aop編程的相關注解。

2.1、@EnableAspectJAutoProxy

先說說@EnableAspectJAutoProxy注解,看看它的源碼:

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(AspectJAutoProxyRegistrar.class) public @interface EnableAspectJAutoProxy { /** * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed * to standard Java interface-based proxies. The default is {@code false}. */ boolean proxyTargetClass() default false; /** * Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal} * for retrieval via the {@link org.springframework.aop.framework.AopContext} class. * Off by default, i.e. no guarantees that {@code AopContext} access will work. * @since 4.3.1 */ boolean exposeProxy() default false; }

這里有兩個方法,一個是控制aop的具體實現方式,為true 的話使用cglib,為false的話使用java的Proxy,默認為false,第二個參數控制代理的暴露方式,解決內部調用不能使用代理的場景,默認為false。

2.2、@Aspect

聲明一個切面(類)上,作用是把當前類標識為一個切面供容器讀取。在切面類中需要定義切面方法用於響應響應的目標方法,切面方法即為通知方法,通知方法需要用注解標識,AspectJ 支持 5 種類型的通知注解:

2.2.1、@Before

前置通知, 在方法執行之前執行。

2.2.2、@After

后置通知, 在方法執行之后執行。

2.2.3、@AfterRunning

返回通知, 在方法返回結果之后執行。

2.2.4、@AfterThrowing

異常通知, 在方法拋出異常之后。

2.2.5、@Around

環繞通知, 圍繞着方法執行。

2.3、@PointCut 

聲明切點,是植入Advice(通知)的觸發條件。每個Pointcut的定義包括2部分,一是表達式,二是方法簽名。方法簽名必須是 public及void型。可以將Pointcut中的方法看作是一個被Advice引用的助記符,因為表達式不直觀,因此我們可以通過方法簽名的方式為 此表達式命名。因此Pointcut中的方法只需要方法簽名,而不需要在方法體內編寫實際代碼。

/** * 日志切面 */ @Component @Aspect public class LoggingAspect { /** * 前置通知:目標方法執行之前執行以下方法體的內容 */ @Before("execution(* com.qcc.beans.aop.*.*(..))") public void beforeMethod(JoinPoint jp){ String methodName = jp.getSignature().getName(); System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs())); } /** * 返回通知:目標方法正常執行完畢時執行以下代碼 */ @AfterReturning(value="execution(* com.qcc.beans.aop.*.*(..))",returning="result") public void afterReturningMethod(JoinPoint jp, Object result){ String methodName = jp.getSignature().getName(); System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】"); } /** * 后置通知:目標方法執行之后執行以下方法體的內容,不管是否發生異常。 * @param jp */ @After("execution(* com.qcc.beans.aop.*.*(..))") public void afterMethod(JoinPoint jp){ System.out.println("【后置通知】this is a afterMethod advice..."); } /** * 異常通知:目標方法發生異常的時候執行以下代碼 */ @AfterThrowing(value="execution(* com.qcc.beans.aop.*.*(..))",throwing="e") public void afterThorwingMethod(JoinPoint jp, NullPointerException e){ String methodName = jp.getSignature().getName(); System.out.println("【異常通知】the method 【" + methodName + "】 occurs exception: " + e); } }

三、全局異常處理

3.1、@ControllerAdvice

包含@Component。可以被掃描到。統一處理異常。

3.2、@ExceptionHandler(Exception.class)

用在方法上面表示遇到這個異常就執行以下方法。

四、JPA注解

4.1、@Entity

4.2、@Table(name=”“)

表明這是一個實體類。一般用於jpa這兩個注解一般一塊使用,但是如果表名和實體類名相同的話,@Table可以省略

4.3、@MappedSuperClass

用在確定是父類的entity上。父類的屬性子類可以繼承。

4.4、@NoRepositoryBean

一般用作父類的repository,有這個注解,spring不會去實例化該repository。

4.5、@Column

如果字段名與列名相同,則可以省略。

4.6、@Id

表示該屬性為主鍵。

4.7、@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = “repair_seq”)

表示主鍵生成策略是sequence(可以為Auto、IDENTITY、native等,Auto表示可在多個數據庫間切換),指定sequence的名字是repair_seq。

4.8、@SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1)

name為sequence的名稱,以便使用,sequenceName為數據庫的sequence名稱,兩個名稱可以一致。

4.9、@Transient

表示該屬性並非一個到數據庫表的字段的映射,ORM框架將忽略該屬性。如果一個屬性並非數據庫表的字段映射,就務必將其標示為@Transient,否則,ORM框架默認其注解為@Basic。@Basic(fetch=FetchType.LAZY):標記可以指定實體屬性的加載方式

4.10、@JsonIgnore

作用是json序列化時將Java bean中的一些屬性忽略掉,序列化和反序列化都受影響。

4.11、@JoinColumn(name=”loginId”)

一對一:本表中指向另一個表的外鍵。一對多:另一個表指向本表的外鍵。

4.12、@OneToOne、@OneToMany、@ManyToOne

對應hibernate配置文件中的一對一,一對多,多對一。

五、事務

5.1、@Transactional

第一步:
在入口處增加 @EnableTransactionManagement 注解

package com.cm.aps; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication @EnableTransactionManagement public class ApsApplication { public static void main(String[] args) { SpringApplication.run(ApsApplication.class, args); } }

第二步就是在Service的類里寫處理過程;注意事項請看注釋

@Override @Transactional(rollbackFor = Exception.class) //這里回滾進行定義 public int update(Prdtv prdtv) throws RuntimeException{ //注意在這里處理業務時,不要使用Try ...異常捕獲,否則不回滾 return prdtvMapper.update(prdtv); }

六、Lombok

6.1、@Slf4j

自動生成該類的 log 靜態常量,要打日志就可以直接打,不用再手動 new log 靜態常量。

public class User{ private static final Logger log = LoggerFactory.getLogger(User.class); public static void main(String[] args){ log.info("hi"); } }
@Slf4j public class User{ public static void main(String[] args){ log.info("hi"); } }

6.2、@Setter

注解在屬性上。為屬性提供 setting 方法。

6.3、@Getter

注解在屬性上。為屬性提供 getting 方法。

6.4、@Data

注解在類上。等同於添加如下注解:

  • @Getter/@Setter

  • @ToString

  • @EqualsAndHashCode

  • @RequiredArgsConstructor

6.5、@Log4j2

注解在類上。為類提供一個 屬性名為log 的 log4j 日志對象,和@Log4j注解類似。

6.6、@EqualsAndHashCode

默認情況下,會使用所有非瞬態(non-transient)和非靜態(non-static)字段來生成equals和hascode方法,也可以指定具體使用哪些屬性。

如果某些變量不想要加進判斷,可以透過 exclude 排除,也可以使用 of 指定某些字段。

@EqualsAndHashCode(exclude = "name") public class User{ private String name; private Integer age; }

6.7、@ToString

生成toString方法,默認情況下,會輸出類名、所有屬性,屬性會按照順序輸出,以逗號分割。

6.8、@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor

無參構造器、部分參數構造器、全參構造器,當我們需要重載多個構造器的時候,只能自己手寫了。

6.8.1、@NoArgsConstructor

注解在類上。為類提供一個無參的構造方法。

6.8.2、@AllArgsConstructor

注解在類上。為類提供一個全參的構造方法。

6.8.3、@RequiredArgsConstructor

生成一個包含 "特定參數" 的構造器,特定參數指的是那些有加上 final 修飾詞的變量。

6.9、@NonNull

注解在屬性上,如果注解了,就必須不能為Null。

6.10、@Nullable

注解在屬性上,如果注解了,就必須可以為Null。

6.11、@Value

也是整合包,但是他會把所有的變量都設成 final 的,其他的就跟 @Data 一樣,等於同時加了以下注解:

  • @Getter (注意沒有setter)

  • @ToString

  • @EqualsAndHashCode

  • @RequiredArgsConstructor

6.12、@Builder

自動生成流式 set 值寫法,從此之后再也不用寫一堆 setter 了。

注意,雖然只要加上 @Builder 注解,我們就能夠用流式寫法快速設定對象的值,但是 setter 還是必須要寫不能省略的,因為 Spring 或是其他框架有很多地方都會用到對象的 getter/setter 對他們取值/賦值。

所以通常是 @Data 和 @Builder 會一起用在同個類上,既方便我們流式寫代碼,也方便框架做事。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM