Search code examples
springioc-container

Spring custom annotation for this behavior


I have code like this.

@org.springframework.stereotype.Component("studentInfo")
@org.springframework.context.annotation.Profile("studentInfo")
public class CustomStudentInfo{

As you can see i have the component name and the same profile i mean i just want to set this class as a bean only when the profile is set and fact this is working but is kind annoying to type this on 2 lines my question is can i have this on a custom annotation i mean a annotation that help me just to write.

@CustomSpringAnnotation("studentInfo")
public class CustomStudentInfo{

Thanks and sorry if the question is plain.


Solution

  • You can "incorporate" the spring annotations into a custom one like (source/proof: SpringBootApplicaiton source code):

    package my.package.annotations;
    
    @org.springframework.stereotype.Component("studentInfo") // needs "constant expression" here 
    @org.springframework.context.annotation.Profile("studentInfo") // .. and here!
    public @interface MyCustomSpringAnnotation { ...
        // but here you have a problem,
        // since you cannot pass (at least not to the above annotations,
        // ... but maybe dynamically *hack* into the spring context):
        String value() default ""; //?
    }
    

    ...then you could use it like:

    @MyCustomSpringAnnotation 
    public class CustomStudentInfo { // ...
    

    but with the fixed "studentInfo" it is no improvement (but the contrary).


    The probably "most spring-like" and best solution (no stress with "too many annotations") is: To consume "studentInfo" from a "visible" (static) final variable (probably best in the affected class):

    @org.springframework.stereotype.Component(CustomStudentInfo.PROFILE_NAME)
    @org.springframework.context.annotation.Profile(CustomStudentInfo.PROFILE_NAME)
    public class CustomStudentInfo {
    
        public static final String PROFILE_NAME = "studentInfo";
        // ...