2012-08-08 65 views
0

在我的使用Spring容器的應用程序中,我創建了自己的註解,並且我希望在運行時獲取用我的註釋註釋的類的Class對象。爲此,我想利用Spring容器。Spring容器 - 空參數的註解

在我的.xml配置文件,我把

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

使被標註了我的問題註解類是由Spring檢測。問題是,這些類沒有任何參數的構造函數,所以現在我有兩個選擇:

  1. 定義無參數的構造函數的類
  2. 定義爲.xml豆子並使用構造帶參數的

但是有可能使用某些註釋來註釋構造函數參數,所以Spring會知道它在創建bean時需要通過null值?

此外,這些bean將具有原型範圍,從應用程序的角度來看,在創建bean期間,構造函數參數的內容是未知的。

編輯: 我不得不使用@Value("#{null}")用於註釋構造函數的參數

回答

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; 
    } 

} 
1

這可能不是你要找的東西,但是如果你想重新使用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; 
    } 
+0

感謝您的摘錄。 – Andna 2012-08-08 12:59:30