spring - 此行为的 Spring 自定义注释
问题描述
我有这样的代码。
@org.springframework.stereotype.Component("studentInfo")
@org.springframework.context.annotation.Profile("studentInfo")
public class CustomStudentInfo{
正如您所看到的,我有组件名称和相同的配置文件,我的意思是我只想在设置配置文件时将此类设置为 bean,并且事实上这是有效的,但是在 2 行上键入它有点烦人我的问题是可以我在自定义注释上有这个,我的意思是帮助我写作的注释。
@CustomSpringAnnotation("studentInfo")
public class CustomStudentInfo{
如果问题很简单,谢谢和抱歉。
解决方案
您可以将弹簧注释“合并”到自定义注释中,例如(来源/证明: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";
// ...
推荐阅读
- javascript - 从 React Query 中的另一个查询的重试中重新获取不同的查询
- php - 如何从 Vue CLI 本地服务器使用 PHP 本地服务器会话
- rest - Keycloak Get Users 返回 403 禁止
- ssl - pycharm的“pip install package”错误
- firebase - Firebase Firestore 3 个随机文档字段的总和低于设定数量
- java - 在 SpringBoot 中出现 NoHandlerFoundException 时无法返回自定义响应
- python - 使用 SMTP 服务器通过 python 发送邮件
- reactjs - 如何模拟与useRef绑定的钩子中使用的回调函数?
- groovy - 在groovy中,当列表为空时如何过滤列表?
- python - AttributeError:“str”对象在从 simpletransformers 训练 QuestionAnsweringModel 时没有属性“to”