簡體   English   中英

如何在擁有對象(也就是@Autowired)上的注釋條件下為@Autowire字段提供其他bean?

[英]How provide a different bean to an @Autowire field conditional on an annotation on the owning object which is also @Autowired?

我有一個配置類,提供了相同基本bean接口的兩個實現。 我希望根據擁有類自動裝配的注釋來有條件地使用它們。

“擁有”類的用法:

public class MyController
{
    @Autowired
    private OwnerInterface baseOwner;

    @Autowired
    @MyAnnotation
    private OwnerInterface specialOwner;
}

所屬類:

public class OwningClass implements OwnerInterface
{
    //This is the one I want to supply a conditional bean for
    @Autowired
    private MyBeanInterface someBean;
}

這是config類的偽代碼:

@Configuration
public class ConfigClass
{
    @Bean
    //Should I use a different conditional?
    //And if I make a static method to use here, how would I pass the owning class to it?
    @ConditionalOnExpression(...elided...)
    public MyBeanInterface getNormalBeanInterface()
    {
        return new MyBeanInterfaceImpl();
    }

    @Bean
    @ConditionalOnExpression(...elided.../* MyAnnotation */)
    public MyBeanInterface getSpecialBeanInterface()
    {
        return new MyBeanInterfaceForMyAnnotation();
    }
}

對於條件,是否有辦法將擁有的對象傳遞給它? 我將使用靜態方法,例如:

@ConditionalOnExpression(
    "#{T(MyAnnotationVerifier).isAnnotatedBy(ownignObject))}"
)

有更好的解決方案嗎?

我不想使用AOP,因為那是在使用應用程序期間,並且增加了每個調用的開銷。 如果我可以提供bean,那么它將在啟動時創建對象。

我可以使用其他@Conditional注釋執行此操作嗎?

如果必須靜態決定(例如@MyAnnotation),則可以使用@Primary

@Bean
@Primary
public MyBeanInterface getNormalBeanInterface()
{
    return new MyBeanInterfaceImpl();
}

@Bean
public MyBeanInterface getSpecialBeanInterface()
{
    return new MyBeanInterfaceForMyAnnotation();
}

這樣,您可以按類型自動連線,它將始終使用@Primary引用bean。


替代方法:按名稱使用自動連線

public class ConfigClass {
    @Bean
    public MyBeanInterface normalBean(){
        return new MyBeanInterfaceImpl();
    }

    @Bean
    public MyBeanInterface specialBean(){
        return new MyBeanInterfaceForMyAnnotation();
    }
}

public class MyController {
    @Autowired
    private OwnerInterface normalBean;

    @Autowired
    private OwnerInterface specialBean;
}

這里要注意:變量名( specialBean / normalBean )在這里MyController比賽正好與在@Bean方法ConfigClass

希望這對您有所幫助。

暫無
暫無

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

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