为了账号安全,请及时绑定邮箱和手机立即绑定

如果当前类是 spring bean,如何使用抽象类的参数调用超级构造函数?

如果当前类是 spring bean,如何使用抽象类的参数调用超级构造函数?

largeQ 2023-04-26 13:56:22
我有两个来自自定义库的类,我无法更改。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);

 }


查看完整回答
反对 回复 2023-04-26
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

这应该工作。如果您像这样实例化您的 bean,则您的 ChildClass 上不需要 @Component 注释。确保您的 bean 定义在配置类 (@Configuration) 中并且您的配置是组件扫描的一部分。


@Configuration

public class Config {

    @Bean

    public BaseClass childClass() {

        return new ChildClass(new CustomParam(5));

    }

}


查看完整回答
反对 回复 2023-04-26
  • 2 回答
  • 0 关注
  • 97 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信