Try   HackMD

Spring 常用註解(Annotation)

tags: Spring Annotation

一、資料庫

@Entity

聲明這個class為實體類,class name即為資料表表名

@Table

可以為資料表、目錄、模型(schema)指定名稱

  • uniqueConstraints 設定唯一值
    • @UniqueConstraint(columnNames = {"name"})

@Id

宣告主鍵

@Basic

宣告可否為空值

@GeneratedValue

用於標註主鍵生成策略,通過strategy屬性可定義以下:
(1)TABLE:通過資料表產生主鍵,此策略有利於資料庫移植
(2)IDENTITY:自動生成ID,Oracle不支持這種方式
(3)SEQUENCR :通過序列配合@SequenceGenerator產生主鍵
(4)AUTO:默認選項,自動選擇合適策略

@Table(name="CUSTOMERS")
@Entity
public class Customer {
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Id
    private Integer id;
    private String name;
    private String email;
    private int age;
 
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

@SequenceGenerator

定義一個序列主鍵產生器

@Column

聲明普通屬性

@Column(name=”category_name” length=20)
    Public void getCategoryName(){
        Return this.categoryName;
    } 

@Temporal

帶入時間:
TemporalType.DATE(日期)
TemporalType.TIME(時間)
TemporalType.TIMESTAMP(日期和時間)

二、控制器

@Controller

聲明為控制器

@RequestMapping

設定請求URL路徑

@ReaponseBody

當返回數據是其他格式數據(json、xml)使用

@RequestBody

POST或者PUT的數據是JSON格式或者XML格式時使用

@RestController

Spring MVC4.0以後:@RestController=@Controller+@ResponseBody

@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping

限制資料以什麼方式接收

@PathVariable

bind到URI template變數的值

@RequestParam

bind(綁定) request parameter(參數)到method的變數

@Configuration

配置spring容器

@Override

複寫method

@Autowired

注入class,取得相關method

@Bean

@Configuration
public class AppConfig {
    @Bean
    public TransferService transferService() {
        return new TransferServiceImpl();
    }
}

等同與於XML中的配置

<beans>
    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
</beans>

@Component

通用註解,以下三個都是這個註解做拓展

@Controller

註解類別可以進行前端請求的處理、轉發、重定向等。

@Service

註解類別處理運算邏輯

@Repository

註解類別作為DAO對象(Data Access Objects),可以直接對資料表進行操作

@EnableGlobalMethodSecurity(securedEnabled=true)即可使用

@Secured

可以設定擁有那些權限可以使用這個method

如果我们要求,「只有」同时擁有設定權限的用户才能使用method,這時候@Secured就無能為力了。

@EnableGlobalMethodSecurity(prePostEnabled=true)即可使用

@PreAuthorize

執行方法前進行權限驗證

@PostAuthorize

先執行方法後再進行權限驗證

Spring Security Reference 表達式

https://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/htmlsingle/#el-common-built-in