Spring Configuration動態繫結bean id
阿新 • • 發佈:2018-10-31
簡述:
對於bean id 可能在注入的時候需要根據配置動態的制定例項
程式碼:
ERepositoryConfigure.java
package com.cpa.components.system.e.repository; 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; } }