【问题标题】:Spring custom annotation for this behavior此行为的 Spring 自定义注释
【发布时间】:2020-02-19 18:33:50
【问题描述】:

我有这样的代码。

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

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

@CustomSpringAnnotation("studentInfo")
public class CustomStudentInfo{

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

【问题讨论】:

  • 在引入自定义注释时,我看到的障碍是,您不能将自定义注释的 value ("studentInfo") 传递给 @Profile/@Component...与“base类”,您只能使用“常量表达式”(也可以是(静态)最终字段)
  • 嗨,谢谢你能提供一些例子

标签: spring ioc-container


【解决方案1】:

您可以将弹簧注释“合并”到自定义注释中,例如(来源/证明: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 ""; //?
}

...那么您可以像这样使用它:

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

【讨论】:

    猜你喜欢
    • 2020-09-10
    • 2019-12-24
    • 2023-04-01
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多