簡體   English   中英

如何在應用程序中獲取 bean 變量的值

[英]How to fetch value of a bean variable inside the application

我有一個用例,我想聲明一個在應用程序啟動時初始化的 bean,稍后我想在條件表達式上使用 bean 的變量下面是代碼片段

// This is the bean I am declaring
@Configuration
public class ABCConfiguration {
    @Bean(name="mybean")
    public ABCConfig abcConfig() {
                // ABCFunction() is a function which returns true/false
        ABCConfig config = new ABCConfig(ABCFunction());
        return config;
        
    }

}
public class ABCConfig {

    private boolean isXYZ;

    public DRConfig(boolean isXYZ) {
        this.isXYZ = isXYZ;
    }

    public boolean isXYZ() {
        return isXYZ;
    }
}

現在我想通過條件表達式上已經注冊的 bean 在我的應用程序中使用變量 isXYZ 的值。 這就是我現在正在嘗試的方式。

@ConditionalOnExpression("${mybean.isXYZ()} == true")

但是我收到以下錯誤表達式解析失敗; 嵌套異常為 org.springframework.expression.spel.SpelParseException: EL1041E: 解析有效表達式后,表達式中仍有更多數據:'lcurly({)'

基於這篇文章,您可以通過多種方法獲得@Bean 的價值,其中一種是:

理解 Spring 中的 getBean()


@Configuration
class AnnotationConfig {

    @Bean(name = {"tiger", "kitty"})
    @Scope(value = "prototype")
    Tiger getTiger(String name) {
        return new Tiger(name);
    }

    @Bean(name = "lion")
    Lion getLion() {
        return new Lion("Hardcoded lion name");
    }

    interface Animal {}
}

 @Autowired
 private ApplicationContext context;

 Tiger tiger = (Tiger) context.getBean("lion");

暫無
暫無

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

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