Spring JavaConfig,bean的自定义范围和注释

时间:2013-03-15 15:12:50

标签: spring configuration annotations scope

我有一个问题需要解决: 1)我们的项目使用Spring JavaConfig方法(所以没有xml文件) 2)我需要创建自定义范围,xml中的示例如下所示:

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
    <map>
        <entry key="workflow">
            <bean
                class="com.amazonaws.services.simpleworkflow.flow.spring.WorkflowScope" />
        </entry>
    </map>
</property>

我用JavaConfig想出它看起来像这样:

    @Bean
public CustomScopeConfigurer customScope () {
    CustomScopeConfigurer configurer = new CustomScopeConfigurer ();
    Map<String, Object> workflowScope = new HashMap<String, Object>();
    workflowScope.put("workflow", new WorkflowScope ());
    configurer.setScopes(workflowScope);

    return configurer;
}

如果我的假设错了,请纠正我。

3)我需要将我的类注释为@Component(scope =“workflow”) 再次xml配置如下所示:

<bean id="activitiesClient" class="aws.flow.sample.MyActivitiesClientImpl" scope="workflow"/>

所以基本上问题是 - 我是否正确使用@Component(scope =“workflow”),或者预计会采用其他方式?

由于

2 个答案:

答案 0 :(得分:8)

您需要使用注释@Scope。像这样:

@Scope("workflow")

也可以创建自定义范围限定符:

@Qualifier
@Scope("workflow")
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface WorkflowScoped {
}

并以这种方式使用它:

@Component
@WorkflowScoped 
class SomeBean

答案 1 :(得分:0)

我在项目中也遇到过类似情况,请参见here

从本质上讲,您必须将WorkflowScope类实例作为参数传递给customScope()方法并使用它;否则,它将无法正常工作:

@Bean
public CustomScopeConfigurer customScope(WorkflowScope workflowScope) {
    CustomScopeConfigurer configurer = new CustomScopeConfigurer();
    Map<String, Object> workflowScope = new HashMap<>();
    workflowScope.put("workflow", workflowScope);
    configurer.setScopes(workflowScope);

    return configurer;
}