Dynamically defining which bean to autowire in Spring (using qualifiers)

前端 未结 2 424
-上瘾入骨i
-上瘾入骨i 2020-12-30 13:08

I have a Java EE + Spring app that favors annotations over XML configuration. The beans always have prototype scope.

I now have in my app business rules that depend

2条回答
  •  难免孤独
    2020-12-30 13:41

    You could provide a Configuration class that will return the correct bean based on the ThreadLocal value. This assumes you are using Spring 3. I did a little test to make sure that the provider method was called on each request. Here's what I did.

    @Configuration
    public class ApplicationConfiguration
    {
        private static int counter = 0;
    
        @Bean( name="joel" )
        @Scope( value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
        List getJoel()
        {
            return Arrays.asList( new String[] { "Joel " + counter++ } );
        }
    }
    

    And referenced the value in my Controller as follows.

    @Resource( name="joel" )
    private List joel;
    

    in your implementation of the provider you could check the ThreadLocal for the locale and return the correct TransactionRules object or something like that. The ScopedProxy stuff is because I was injecting into a Controller, which is Singleton scoped whereas the value is request scoped.

提交回复
热议问题