Spring Configuration动态绑定bean id

2018-03-21 21:54:16
836次阅读
0个评论
简述:

对于bean id 可能在注入的时候需要根据配置动态的制定实例



代码:

ERepositoryConfigure.java

import org.apache.commons.lang3.Validate;  
import org.springframework.beans.factory.annotation.Autowire;  
import org.springframework.beans.factory.annotation.Value;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
  
import com.cpa.components.system.e.repository.impl.EDBRespository;  
import com.cpa.components.system.e.repository.impl.ERemoteRepository;  
  
@Configuration  
public class ERepositoryConfigure {  
  
    @Value("${cpa.server.e.repository.group.type}")  
    private String type;  
      
    private ERepository repository;  
      
    @Bean(autowire = Autowire.BY_TYPE, name = "components.system.ERepository")  
    public ERepository instance() {  
  
        if (repository != null) {  
            return repository;  
        }  
  
        switch (type) {  
        case "remote_system":  
            repository = new ERemoteRepository();  
            break;  
        case "local_db":  
            repository = new EDBRespository();  
            break;  
        default:  
            break;  
        }  
  
        Validate.notNull(repository, "invalid e repository type:[%s]", type);  
        return repository;  
    }  
}
收藏00

登录 后评论。没有帐号? 注册 一个。