springspring-bootjava-annotations

How to set boolean field for annotation


I am learning Spring annotation

public @interface Autowired {
    boolean required() default true;
}

public @interface Lazy {
    boolean value() default true;
}

here is what I have:

@Autowired(false) - wrong
@Autowired(required=false) - correct

@Lazy(false)  - correct
@Lazy(value = false) - correct

Why Autowired(false) is wrong and @Lazy(false)is correct?


Solution

  • If there is attribute named value, then the name may be omitted, as in:

    public @interface Lazy {
        boolean value() default true;
    }
    
    @Lazy(false)
    

    If there is no attribute named value, you can assign a value by specifying it explicitly:

    public @interface Autowired {
        boolean required() default true;
    }
    
    @Autowired(required = false)
    

    To briefly exemplify; If the @Autowired annotation was as follows, you could use it like the @Lazy annotation.

    public @interface Autowired {
        boolean value() default true;
    }
    
    @Autowired(false)