我有兩個來自自定義庫的類,我無法更改。Bass 類只有帶有自定義參數的構造函數,那不是一個 bean。我想通過子構造函數傳遞參數,但我不知道該怎么做,所以請幫忙)我試過這個,但沒有用。想法在子構造函數中下劃線參數。@Beanpublic ChildClass childClass() { return new ChildClass(new CustomParam(5));}基類 - 不能使用@Component,庫中的那個類public abstract class BaseClass {private CustomParam customParam;protected BaseClass(CustomParam customParam) { this.customParam = customParam;}public Integer getCustomParam() { return customParam.getParamValue();}}兒童班。我自己的擴展@Componentpublic class ChildClass extends BaseClass {//idea underline customParam "could not autowire"public ChildClass(CustomParam customParam) { super(customParam);}}參數類 - 不能使用@Component,庫中的那個類public class CustomParam {private Integer paramValue;public CustomParam(Integer paramValue) { this.paramValue = paramValue;}public Integer getParamValue() { return paramValue;}public void setParamValue(Integer paramValue) { this.paramValue = paramValue;}}
2 回答

湖上湖
TA貢獻2003條經驗 獲得超2個贊
CustomParam不需要用@Component注解來注解,你仍然可以使用@Bean注解將它聲明為bean
配置類
@Bean
public ChildClass childClass() {
return new ChildClass(customParam());
}
@Bean
public CustomParam customParam() {
return new CustomParam(5);
}

慕桂英546537
TA貢獻1848條經驗 獲得超10個贊
這應該工作。如果您像這樣實例化您的 bean,則您的 ChildClass 上不需要 @Component 注釋。確保您的 bean 定義在配置類 (@Configuration) 中并且您的配置是組件掃描的一部分。
@Configuration
public class Config {
@Bean
public BaseClass childClass() {
return new ChildClass(new CustomParam(5));
}
}
添加回答
舉報
0/150
提交
取消