簡體   English   中英

焊接 - 從掃描/beans.xml 中排除應用程序范圍的 bean

[英]WELD - exclude application scoped bean from scanning / beans.xml

我有以下@ApplicationScoped bean:

@ApplicationScoped
public class ServiceProducer {

    private static final Logger logger = LoggerFactory.getLogger(ServiceProducer.class);

    @Default
    @Produces
    @PersistenceContext(unitName = "nemo")
    private EntityManager nemoEntityManager;

    private CacheManager cacheManager;

    @PostConstruct
    void init() {
        try {
            cacheManager = Caching.getCachingProvider().getCacheManager(
                    Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("/ehcache.xml")).toURI(),
                    Thread.currentThread().getContextClassLoader());
        } catch (URISyntaxException e) {
            logger.error(e.getMessage());
        }

    }


    @Produces
    public CacheManager produceCacheManager() {
        return cacheManager;
    }

上述 class 包含在我的 web 應用程序的公共/共享模塊中。 這對生產有好處,但是我需要一個集成測試的替代方案,它是使用 Cucumber 和 wildspike 集成完成的。

通過配置beans.xml,不幸的是我無法禁用上面的bean,我嘗試以這種方式配置beans.xml:

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://xmlns.jcp.org/xml/ns/javaee
    http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all">

    <scan>
        <exclude name="it.myapp.ecommerce.commons.resource.ServiceProducer"></exclude>
    </scan>
    

但是沒有任何改變。 是因為 class 屬於依賴項嗎?

你基本上有兩個選擇。

首先,這是通常推薦的選項,它是您聲明的輔助 bean 上的@Alternative加上@Priority組合,並且僅在測試環境中添加。 這樣,它將被用於測試,但不會被用於生產。 請注意,您必須只在測試環境中添加替代品,否則它會一直被拾取。 例如,您可以直接在測試項目(或其源)下聲明此 bean,以便主(生產)JAR 不包含它。 此外,您無需更改beans.xml即可實現上述目的。 可以通過@Prioritybeans.xml啟用替代方案 前者是全局的,后者是 per-bean-archive。

第二個選項是 CDI 擴展,它將觀察ProcessAnnotatedType<ServiceProducer>事件並veto()正確的 class。 這意味着給定的 class 不會作為 bean 被拾取。 這可以根據某些參數或您手頭的任何其他參數有條件地完成。 鑒於您執行上述操作,您需要以某種方式添加ServiceProducer的新測試實現。 您可以再次通過在測試源中聲明它來做到這一點(此處無需替代),但您也可以使用相同的擴展通過BeanConfigurator SPIAfterBeanDiscovery中注冊合成 bean。

雖然 CDI 擴展非常強大,但我建議您使用第一個選項,一旦您閱讀了一些關於替代方案及其啟用的工作原理,它會更簡單、更容易理解。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM