开发者

Conditional dependency injection

开发者 https://www.devze.com 2023-02-25 18:37 出处:网络
I have an application which is using annotation annotation based dependency injection for service and dao layers. Now it is required that one some condition some of the dao will operate on in memory d

I have an application which is using annotation annotation based dependency injection for service and dao layers. Now it is required that one some condition some of the dao will operate on in memory data-structures instead of db. So, I am thinking of writing new implementations of those dao. Since the service already has annotations with name of dao's, I am not sure how to inject the 开发者_开发百科in-memory ones to it.

Should I overwrite db ones with in-memory ones after injection or there is another clean way? Had I used xml, I would have used a different xml for in-memory dao.

Thanks in advance, Aman


If your in memory dao class only exists (more exctly: only found while class scan) in the cases where it should be used, than you can at @Primary to it.

@Primary indicates that the bean should be given preference when multiple candidates are found.

May you should also have a look at the Spring 3.1 feature: Profiles.

An other way would be to write an Configuration, that depending on some environment Parameter return the correct bean annotated with at primary:

/**
 * I never have tried to inject a bean in a @Configuratution and
 * return it as @Bean annotated it with @Primary, so it is an experiment 
 * I would been glad to know if it works.
 */
@Configuration
public class Switch {
    @Value("#{systemProperties.inmemmory}") 
    private boolean inMemmory;

    @Resource
    @Qualifier("normal")
    private Dao normalDao;

    @Resource
    @Qualifier("inMemmory")
    private Dao inMemoryDao;

    @Bean
    @Primary
    public Dao dao() {
        if (inMemmory) {
            return inMemory;
        } else {
           return normalDao;
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号