2012-09-06 58 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

相关问题