我使用的是Spring Boot3.2,并且我正在try 编写一个注释来导入一些Spring配置.这是我所拥有的:

@Configuration
public class CustomAutoConfiguration {

    @Bean
    public CustomBean customBean() {      
        return new CustomBean();
    }
}

然后我有这样的注解:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(CustomAutoConfiguration.class)
public @interface EnableCustomAutoConfiguration {
}

然后我可以像这样启用:

@SpringBootApplication
@EnableCustomAutoConfiguration
public class MySpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

但我需要CustomBean包含@EnableCustomAutoConfiguration批注中指定的一些值.例如,如果我这样修改EnableCustomAutoConfiguration:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(CustomAutoConfiguration.class)
public @interface EnableCustomAutoConfiguration {
   String someString();
}

然后,我希望在CustomAutoConfiguration中可以访问someString:

@Configuration
public class CustomAutoConfiguration {

    @Bean
    public CustomBean customBean() {      
        String someString = ?? // How can I get the value of "someString" defined in the annotation?
        return new CustomBean(someString);
    }
}

我怎样才能做到这一点呢?

推荐答案

您可以通过ApplicationContext找到带注释的Bean

类似于:

 @Bean
 public CustomBean customBean(ApplicationContext applicationContext) {      
    // get the annotated bean name
    Optional<String> customAutoConfigurationBeanName = 
      applicationContext.getBeansWithAnnotation(EnableCustomAutoConfiguration.class)
                        .keySet().stream().findFirst();
   if (customAutoConfigurationBeanName.isEmpty()) return null;
   // get the EnableCustomAutoConfiguration annotation
   EnableCustomAutoConfiguration enableCustomAutoConfiguration = 
     applicationContext.findAnnotationOnBean(customAutoConfigurationBeanName.get(),
                        EnableCustomAutoConfiguration.class);
  return new CustomBean(enableCustomAutoConfiguration.someString());
}

Java相关问答推荐

Java字符串常数池困惑

@ EnableRouting注释在Kotlin项目中不工作

Java Streams在矩阵遍历中的性能影响

转换为Biggram

H2弹簧靴试验跌落台

Spark上下文在向Spark提交数据集时具有内容,但Spark在实际构建它时发现它为空

名称冲突具有相同的擦除

对Java中的通配符参数的混淆

JPanel透支重叠的JComcoBox

如何正确创建序列图?

试着做一个2x2的魔方求解算法,我如何找到解路径(DFS)?

如何从JNI方法正确调用NSOpenPanel以在正确的线程上运行?

如何在 spring 数据的MongoDB派生查询方法中使用$EXISTS

如何使用路径过渡方法使 node 绕圆旋转?

从Spring6中的JPMS模块读取类时出现问题

在一行中检索字符分隔字符串的第n个值

如何制作回文程序?

具有多个分析模式的复杂分隔字符串的正则表达式

Intellij 2023 IDE:始终在顶部显示菜单栏

java.lang.ClassCastException:com.google.firebase.FirebaseException无法转换为com.google.fire base.auth.FirebaseAuthException