Spring JavaConfig、bean的自定义作用域和注解

13
我有一个需要解决的问题: 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") 是正确的吗?还是应该以其他方式进行?
谢谢。

1
我刚刚收到了警告 @Bean 方法 getWorkflowScope 是非静态的,并返回一个可分配给 Spring 的 BeanFactoryPostProcessor 接口的对象。这将导致在方法所在的 @Configuration 类中无法处理注释,如 @Autowired@Resource@PostConstruct。为避免这些容器生命周期问题,请将此方法添加 static 修饰符。只是提醒一下,你的方法应该写成 @Bean public static CustomScopeConfigurer。 - Brian Schlenker
2个回答

9
您需要使用注解@Scope。像这样:
@Scope("workflow")

也可以创建自定义的作用域限定符:

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

然后这样使用:

@Component
@WorkflowScoped 
class SomeBean

此外,由于原始问题使用 AWS Simple Workflow 生成这些类,使用 AspectJ,因此您需要在配置类中使用 @Bean@Scope("workflow")/@WorkflowScoped - mkobit

0

我在我的项目中遇到了类似的情况,可以看看这里

实质上,你必须将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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接