注解

Java注解

  • @Deprecated:標(biāo)記方法或類過(guò)時(shí)
  • @SuppressWarning: 在確定結(jié)果的前提下忽略警告

第三方注解

  • @Autoware

按運(yùn)行機(jī)制分

  • 源碼注解(SOURCE):只在源碼中存在
  • 編譯時(shí)注解(CLASS):源碼和.class文件時(shí)都存在。@Override
  • 運(yùn)行時(shí)注解(RUNTIME): 源碼和.class文件存在、程序運(yùn)行時(shí)也存在。@Autoware

按來(lái)源分

  • JDK
  • 第三方
  • 自定義
    元注解 :給注解用的注解

自定義注解

  1. 語(yǔ)法:
  • 使用@interface關(guān)鍵字
  • 成員變量要生命成無(wú)參函數(shù)形式,并且無(wú)異常,只能是基本數(shù)據(jù)類型和String,使用default關(guān)鍵字賦默認(rèn)值
  • 只有一個(gè)成員變量時(shí),必須命名為value()
@Target({ElementType.METHOD,ElementType.TYPE})
@Rentention(RententionPolicy.RUNTIME)
@Inherited
@Document
public @interface Discription{
  String desc();
  String author();
  int age() default 18;
}
  1. 元注解
  • @Target:注解適用范圍,可以設(shè)置多個(gè)。
    取值:
ElementType.CONSTRUCTOR
ElementType.FIELD
ElementType.LOCAL_VARIABLE //局部變量
ElementType.METHOD
ElementType.PACKAGE
ElementType.PARAMETER
ElementType.TYPE //類,接口
  • @Rentention:注解生命周期
    取值:
RententionPolicy.SOURCE // 源碼
RententionPolicy.CLASS // 編譯
RententionPolicy.RUNTIME //運(yùn)行
  • @Inherited:允許注解繼承
  • @Document:生成doc時(shí)生成注解信息
  1. 使用注解
@Discription(desc="我是一段描述",author="yujian",age=18)
public String getMyName(){
  return "yujian";
}
  1. 解析注解
    通過(guò)反射獲取類運(yùn)行時(shí)注解信息,從而動(dòng)態(tài)控制類的運(yùn)行邏輯。

實(shí)戰(zhàn)

自定義table和column注解映射字段和表,查詢數(shù)據(jù),打印書(shū)SQL
table和column注解:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {
    String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    String value();
}

User類使用table和column注解

@Table("user")
public class User {

    @Column("id")
    private String id;

    @Column("name")
    private String name;

    @Column("email")
    private String email;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

根據(jù)注解獲取標(biāo)名和字段名,根據(jù)反射獲取字段值:

        //獲取class
        Class c = user.getClass();
        //獲取table名稱
        if (!c.isAnnotationPresent(Table.class)){
            return null;
        }
        Table table = (Table) c.getAnnotation(Table.class);
        System.out.println(table.value());
        //獲取field名稱
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields){
            if (field.isAnnotationPresent(Column.class)){
                Column column = field.getAnnotation(Column.class);
                System.out.print(column.value() + ":");
                //通過(guò)反射獲取對(duì)象值
                String fieldName = field.getName();
                String methodName = "get"
                        + fieldName.substring(0,1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    Method method = c.getMethod(methodName);
                    System.out.println(method.invoke(user));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

常見(jiàn)概念

  • 為什么需要把 @Autowired寫(xiě)在構(gòu)造器上:注入注解要等類構(gòu)造完成才會(huì)注入外部依賴,但變量是按順序加載的,容易出現(xiàn)空指針異常,使用構(gòu)造器注入在調(diào)用時(shí)去初始化,能保證已經(jīng)注入了外部依賴。

  • @Autowired只按照byType 注入;
    @Resource默認(rèn)按byName自動(dòng)注入,也提供按照byType 注入;

  • @Configuration:配置文件,與@Bean連用可配置單個(gè)Bean,eg.@Bean(name="user")

  • @EnableAutoConfiguration:配合spring.factories文件將配置文件裝配到spring中,參考。

  • @ComponentScan:疊加在配置文件類上,可以定策略掃描Bean,默認(rèn)掃描配置文件同包的類,注意類上需要配置

//@Component注解。basePackages定義掃描的包
@ComponentScan(basePackages = { ” com.springboot . chapter3 . pojo” })
//basePackageClasses 定義掃描的類
@ComponentScan(basePackageClasses = {User. class} ) 
//還有 includeFilters 和 excludeFilters 
@ComponentScan(basePackages = "com.springboot.chapter3 . * ”, excludeFilters = {@Filter(classes = {Service . class})}) 。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容