0

So I have a class structure like so:

public class A {
    private String foo;

    protected A() {};

    protected A(String foo) {
        this.foo = foo;
    }

    public String getFoo() {
        return foo;
    }
}

public class B extends A {
    public B() {};

    public String getSomething(String test) {
        return super.getFoo() + test;
    }
}

public class C extends A {
    public C() {};

    public String getSomethingElse(String test) {
        return super.getFoo() + test;
    }
}

Here are my java configuration files:

@Configuration
public class ConfigA {
    @Bean
    public A a() {
        return new A("FinalString");
    }
}

@Configuration
public class ConfigChildren {
    @Bean
    public B b() {
        return new B();
    }

    @Bean
    public C c() {
        return new C();
    }
}

Obviously the problem is that the super value is the child classes are null so doing super.getFoo will be null even though the configuration is initialized.

I'm wondering how to connect these two in the configuration. I know in spring XML there's a way to do it with the parent field but I don't know how to do that in java config.

I tried playing around with singletons but I don't think that's really applicable or good practice here. Is there a way to initialize A for the child classes without passing the string variable into every child and having it do super(foo). Or is that the only way to do it?

Richard
  • 5,840
  • 36
  • 123
  • 208
  • Your code won't compile at the moment. Do you have a parameterless constructor in `A` in your actual code? – Savior Apr 05 '16 at 15:57
  • @Pillar no my code compiles, it has the same constructor as above. I want to initialize it with the string value i pass in like i do above in the config class. And I want all the child classes to have access to that string. – Richard Apr 05 '16 at 16:01
  • Your code above will not compile because `B` and `C` aren't invoking the only constructor in `A` which takes an argument. – Savior Apr 05 '16 at 16:02
  • @Pillar sorry i added the default constructor.....i guess now that i'm typing it out it seems im gonna have to pass in the string to every child class and have them do `super(stringFoo)`? – Richard Apr 05 '16 at 16:05
  • Pretty much. Or, if that string value is meant to be a default value, your parameterless constructor can set it itself. – Savior Apr 05 '16 at 16:06
  • @Pillar well that string is read in by spring from the `application.properties` file. So I guess I'll just pass it in. I just don't like length constructors..... – Richard Apr 05 '16 at 16:07
  • @Richard If you are looking for `parent` attribute equivalent, it is not supported with `annotations`. Please check http://stackoverflow.com/questions/35199294/bean-inheritance-via-annotation/35199917#35199917 – Madhusudana Reddy Sunnapu Apr 05 '16 at 16:34

0 Answers0