【问题标题】:Spring JavaConfig, bean's custom scopes and annotationsSpring JavaConfig,bean 的自定义作用域和注解
【发布时间】:2013-03-15 15:12:49
【问题描述】:

我有一个问题要解决: 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") 还是预期以其他方式?

谢谢

【问题讨论】:

  • 我刚刚收到警告 @Bean method getWorkflowScope is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues. 仅供参考,您的方法应该是 @Bean public static CustomScopeConfigurer

标签: spring configuration annotations scope


【解决方案1】:

您需要使用注解@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。跨度>
【解决方案2】:

我在我的项目中遇到过类似的情况,请参阅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;
}

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 2014-09-02
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2015-06-10
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多