Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JavaConfig, bean's custom scopes and annotations

I have a problem to solve: 1) our project is using Spring JavaConfig approach (so no xml files) 2) I need to create custom scope, example in xml looks like this:

<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>

I figured it out with JavaConfig it will looks something like this:

    @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;
}

Correct me if I'm wrong with my assumption.

3) I need to annotate my class something as @Component (scope="workflow") again xml configuration would look like this:

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

So basically the question is - am I right with my assumption to use @Component (scope="workflow") or it is expected to be in some other way?

Thanks

like image 387
user2174470 Avatar asked Mar 15 '13 15:03

user2174470


People also ask

What is bean scope in Spring using annotation?

In Spring, scope can be defined using spring bean @Scope annotation. Let's quickly list down all six inbuilt bean scopes available to use in spring application context. These same scope apply to spring boot bean scope as well. Opposite to singleton, it produces a new instance each and every time a bean is requested.

Is @bean method level annotation?

@Bean is a method-level annotation and a direct analog of the XML <bean/> element. The annotation supports most of the attributes offered by <bean/> , such as: init-method , destroy-method , autowiring , lazy-init , dependency-check , depends-on and scope .

Which annotation is used for defining beans?

We can also declare beans using the @Bean annotation in a configuration class. Finally, we can mark the class with one of the annotations from the org.


1 Answers

You need to use annotation @Scope. Like this:

@Scope("workflow")

It is also possible to create custom scope qualifier:

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

and use it this way:

@Component
@WorkflowScoped 
class SomeBean
like image 59
Michail Nikolaev Avatar answered Nov 27 '22 21:11

Michail Nikolaev