Spring Configuration动态绑定bean id

简述:

对于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;
	}
}










猜你喜欢

转载自blog.csdn.net/anialy/article/details/40044119