Spring对此行为的自定义注释

问题描述 投票:0回答:1

我有这样的代码。

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

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

@CustomSpringAnnotation("studentInfo")
public class CustomStudentInfo{

谢谢您,如果问题很明显。

spring ioc-container
1个回答
0
投票
您可以将spring注释“合并”到一个自定义的注释中,例如(源/证明: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: String value() default ""; //? }

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

@MyCustomSpringAnnotation public class CustomStudentInfo {

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


与(抽象的)“基类”方法相同。您可以通过继承来“传输”(春季,更好:)java批注,但是您在这里面临相同的问题,需要在“批注时间”处使用“常量表达式”:)

@org.springframework.stereotype.Component("problem here") @org.springframework.context.annotation.Profile(SomeVisibleClass.SOME_CONSTANT) // .. is (also in above) possible. public abstract class MyAbstractCustomProfiledBeanBase { }

使用方式:

public class CustomStudentInfo extends MyAbstractCustomProfiledBeanBase { ...

© www.soinside.com 2019 - 2024. All rights reserved.