首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Spring 依賴注入切換 Dao 實現:XML 配置 `ref` 屬性指向不同 Bean ID,或用 @Qualifier/@Profile 註解切換

     編輯:程式設計綜合問答

場景:`ServiceImpl` 依賴 `Dao` 接口,有 `DaoImpl`、`DaoImpl1` 兩個實現,需通過配置切換。

XML 配置切換(傳統)

<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>

註解配置切換(現代 Spring 3+)

方式一:@Qualifier 指定 Bean 名稱

@Service
public class ServiceImpl implements Service {
    @Autowired
    @Qualifier("daoImpl")  // 或 "daoImpl1"
    private Dao dao;
}

方式二:@Profile 環境隔離

@Repository
@Profile("dev")
public class DaoImpl implements Dao { ... }

@Repository
@Profile("prod")
public class DaoImpl1 implements Dao { ... }

// 啟動時指定 -Dspring.profiles.active=dev

方式三:@Primary 設定默認,配合 @ConditionalOnProperty

@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`,鍵為 Bean 名稱(小寫類名)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved