場景:`ServiceImpl` 依賴 `Dao` 接口,有 `DaoImpl`、`DaoImpl1` 兩個實現,需通過配置切換。
<bean name="daoImpl" class="com.example.DaoImpl" />
<bean name="daoImpl1" class="com.example.DaoImpl1" />
<bean name="serviceImpl" class="com.example.ServiceImpl">
<property name="dao" ref="daoImpl" /> <-- 改成 daoImpl1 即可切換
</bean>
@Service
public class ServiceImpl implements Service {
@Autowired
@Qualifier("daoImpl") // 或 "daoImpl1"
private Dao dao;
}
@Repository
@Profile("dev")
public class DaoImpl implements Dao { ... }
@Repository
@Profile("prod")
public class DaoImpl1 implements Dao { ... }
// 啟動時指定 -Dspring.profiles.active=dev
@Repository
@Primary
@ConditionalOnProperty(name = "dao.type", havingValue = "v1", matchIfMissing = true)
public class DaoImpl implements Dao { ... }
@Repository
@ConditionalOnProperty(name = "dao.type", havingValue = "v2")
public class DaoImpl1 implements Dao { ... }
@Service
public class ServiceImpl implements Service {
private final Map daoMap;
private Dao currentDao;
public ServiceImpl(Map daoMap) {
this.daoMap = daoMap;
this.currentDao = daoMap.get("daoImpl"); // 默認
}
public void switchDao(String key) {
Dao dao = daoMap.get(key);
if (dao != null) this.currentDao = dao;
}
}
Spring 容器自動將所有 `Dao` 實現收集進 `Map