【问题标题】:Spring container - annotation for null argumentSpring容器-空参数的注释
【发布时间】:2012-08-08 10:12:09
【问题描述】:

在我使用 Spring 容器的应用程序中,我创建了自己的注解,并且我希望在运行时获取使用我的注解进行注解的类的 Class 对象。为此,我想使用 Spring 容器。

在我的 .xml 配置文件中放置

<context:component-scan base-package="some.package" >
   <context:include-filter type="annotation" expression="some.package.Question" />
</context:component-scan>

因此 Spring 检测到使用我的 Question 注释注释的类。问题是这些类没有参数构造函数,所以现在我有两个选择:

  1. 在这些类中定义无参数构造函数
  2. 在.xml 中定义bean 并使用constructor-arg

但是是否可以用一些注解来注解构造函数参数,所以 Spring 会知道它需要在创建 bean 期间传递 null 值?

这些 bean 也将具有原型范围,并且从应用程序的角度来看,构造函数参数的内容在创建 bean 期间是未知的。

编辑: 我不得不使用 @Value("#{null}") 注释构造函数参数

【问题讨论】:

    标签: spring dependency-injection


    【解决方案1】:

    我认为您使用无参数构造函数的第一个建议听起来更干净-原因是,从您的角度来看,即使实例变量具有空值,创建的对象也被认为已正确初始化-这可以通过默认构造函数

    如果无法更改,您使用 @Value("#{null}") 的方法也可以,我可以在测试用例中进行测试:

    @MyAnnotation
    public class Component1 {
        private String message;
    
        @Autowired
        public Component1(@Value("#{null}") String message){
            this.message = message;
        }
    
        public String sayHello(){
            return this.message;
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      这可能不是你要找的,但如果你想重用 Spring 的类路径扫描器并将其包装在你自己的实现中,你可以使用以下;

      Class annotation = [your class here ];
      String offsetPath = [your path here ];
      
      // Scan a classpath for a given annotation class
      ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
      
      // MZ: Supply the include filter, to filter on an annotation class
      scanner.addIncludeFilter(new AnnotationTypeFilter(annotation));
      
      for (BeanDefinition bd : scanner.findCandidateComponents(offsetPath))
      {
          String name = bd.getBeanClassName();
          try
          {
              Class classWithAnnotation = Class.forName(name);
      
          }
          catch (Exception e)
          {
              //Logger.fatal("Unable to build sessionfactory, loading of class failed: " + e.getMessage(), e);
              return null;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-24
        • 1970-01-01
        • 1970-01-01
        • 2013-06-19
        • 2012-05-07
        • 1970-01-01
        • 2011-05-17
        • 2012-03-20
        相关资源
        最近更新 更多