首页 > 解决方案 > 此行为的 Spring 自定义注释

问题描述

我有这样的代码。

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

正如您所看到的,我有组件名称和相同的配置文件,我的意思是我只想在设置配置文件时将此类设置为 bean,并且事实上这是有效的,但是在 2 行上键入它有点烦人我的问题是可以我在自定义注释上有这个,我的意思是帮助我写作的注释。

@CustomSpringAnnotation("studentInfo")
public class CustomStudentInfo{

如果问题很简单,谢谢和抱歉。

标签: springioc-container

解决方案


您可以将弹簧注释“合并”到自定义注释中,例如(来源/证明:SpringBootApplicaiton 源代码):

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 ""; //?
}

...然后您可以像这样使用它:

@MyCustomSpringAnnotation 
public class CustomStudentInfo { // ...

但是使用固定的“studentInfo”并没有改善(相反)。


可能“最像弹簧”和最好的解决方案(没有“太多注释”的压力)是:"studentInfo"从“可见”(静态)最终变量中消耗(可能是受影响类中最好的):

@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";
    // ...

推荐阅读