Wednesday, September 9, 2015

Creating Your Own Annotation

Create Annotation using @Interface

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceType {

    Type[] value() default {Type.GENERIC_STUDENT_SERVICE};

}

public enum Type {

    GENERIC_STUDENT_SERVICE(Constants.GENERIC_BEAN_NAME),
    SPECIAL_STUDENT_SERVICE(Constants.SPECIAL_BEAN_NAME);

    private final String name;

    private Type(String name){
        this.name = name;
    }

    public String getName(){
        return name;
    }

    @Override
    public String toString(){
        return this.name;
    }

}

Applying Annotation  
 
@ServiceType(Type.GENERIC_STUDENT_SERVICE)
public class StudentManager {


    public void afterPropertiesSet() throws Exception {
        ServiceType type = getClass().getAnnotation(ServiceType.class);
        Type[] types = type.value();
        if(types!=null && types.length!=0){
            switch(types[0]){
                case GENERIC_STUDENT_SERVICE:
                    // do something ...
                    break;
                case SPECIAL_STUDENT_SERVICE:
                    // do something
                    break;
                default:
                    studentService = context.getBean(Constants.GENERIC_BEAN_NAME, StudentService.class);
                    break;
            }
        }
    }

}