簡體   English   中英

使用Spring注釋將Bean注入具有屬性占位符的構造函數參數

[英]Injecting Beans using Spring Annotations into Constructor Parameters with Property Placeholder

我無法將Bean類型從屬性文件注入到構造函數參數中。 我可以通過將值直接傳遞給@Qualifier(“ beanName”)來注入它,如下所示。

@Component("circle")
public class Circle implements Shape {

}

@RestController  
class MyController {    
    private final Shape shape;

    @Autowired
    public MyClass(@Qualifier("circle")
            Shape shape) {
    this.shape = shape;     
    }
}

但是,下面的代碼示例不起作用。

這將返回Null。

@RestController
class MyController {    
    private final Shape shape;

    @Autowired
    public MyClass(@Qualifier("${shape}")
            Shape shape) {
    this.shape = shape;     
    }
}

如此處所述,使用@Resource(name =“ $ {shape}”)代替@Qualifier進行了嘗試( 春季:將@Qualifier與Property Placeholder一起使用 ),但得到了編譯器錯誤“'@Resource'不適用於參數”

@Resource(“ $ {shape}”)給出錯誤“無法找到方法'value'”

這也行不通:

@RestController
class MyController {    
    @Value("${shape}")
    private final String shapeBean; //Compiler error : "Variable 'shapeBean' might not have been initialised"
    //Not declaring shapeBean as final will give a compiler error at @Qualifier: "Attribute value must be constant"
    private final Shape shape;

    @Autowired
    public MyClass(@Qualifier(shapeBean)
            Shape shape) {
    this.shape = shape;     
    }
}

下面的代碼也不起作用。 在@Qualifier處給出編譯器錯誤:“屬性值必須恆定”。

@RestController
class MyController {    
    @Value("${shape}")
    private final String shapeBean;
    private final Shape shape;

    @Autowired
    public MyClass(@Qualifier(shapeBean)
            Shape shape) {
    this.shape = shape;     
    }
}

還嘗試了以下方法。 兩者都在嘗試訪問形狀時引發NullPointerException。

@Resource(name="${shape}")
private Shape shape; // In addition, throws a warning saying, "Private field 'shape' is never assigned"

@Autowired  
@Resource(name="${shape}")
private Shape shape;

如果構造函數參數是基元或字符串,則可以使用@Value(“ $ {shape}”)並將值注入變量。 但是由於它是一門課,所以我不確定如何完成它。
有人可以告訴我配置不正確或應該做什么嗎?

Circle不會實現Shape中定義的所有方法嗎? -只要符合形狀的規定,就可以了。 現在,如果存在多個形狀,例如Triangle,Rectangle和Circle,並且由於某些原因要動態加載確切的子類,則可能需要使用ApplicationContext.getBean(“”)獲得特定的bean。

您可以通過重寫afterPropertiesSet()來維護對各種可能形狀的引用-查看InitialingBean並在運行時使用正確的bean。

暫無
暫無

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

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