2012-09-06 27 views
3

我想在Activiti中使用Spring表達式語言引用JPA存儲庫。但是,由於Spring使用<jpa:repositories/>創建存儲庫bean,因此它們沒有與它們關聯的標識。有沒有辦法使用SpEL引用某種類型的bean而不是id?我嘗試使用我認爲是LocationRepository的生成名稱(locationRepository),但沒有成功。引用沒有ID的bean

回答

1

我假設LocationRepository是一個接口,以及正在爲您生成的底層實現。當Spring創建一個bean並且沒有明確指定id時,它通常使用實現類的類名來確定bean id。因此,在這種情況下,您的LocationRepository的ID可能是生成的類的名稱。

但是由於我們不知道它是什麼,我們可以創建一個Spring FactoryBean,它通過自動裝配從應用上下文獲得LocationRepository,並以新名稱將其放回到應用上下文中。

public class LocationRepositoryFactoryBean extends AbstractFactoryBean<LocationRepository> { 
    @Autowired 
    private LocationRepository bean; 

    public Class<?> getObjectType() { return LocationRepository.class; } 
    public Object createInstance() throws Exception { return bean; } 
} 

在你的應用程序上下文的xml:

<bean name="locationRepository" class="your.package.LocationRepositoryFactoryBean"/> 

然後,您應該能夠引用您LocationRepository對象與bean ID locationRepository。

+0

對不起,我在長週末之前發佈了這個延遲。它是有道理的,他們的bean名稱是生成的類而不是接口名稱,這就是爲什麼我不能引用它。感謝您的可能解決方案! – redZebra2012

0

不知道如何在SPEL中執行此操作,但可以使用@Qualifier來決定應該注入哪個bean。

如果你想要的話,你可以創建自己的定製@Qualifier註解和訪問bean的基礎上。

@Target({ElementType.FIELD, ElementType.PARAMETER}) 
@Retention(RetentionPolicy.RUNTIME) 
@Qualifier // Just add @Qualifier and you are done 
public @interface MyRepository{ 

} 

要注入它現在使用的倉庫豆和其他地方@MyRepository註解。

@Repository 
@MyRepository 
class JPARepository implements AbstractRepository  
{ 
    //.... 
} 

其注入

@Service 
class fooService 
{ 
    @Autowire 
    @MyRepositiry 
    AbstractRepository repository; 

} 
+0

不完全解決我的問題,但很好知道,感謝您的輸入=) – redZebra2012

相關問題