Question

It is possible in spring to inherit from an abstract class, and let the implementation automatically create an instance of any @Bean annotated method?

Example:
abstract class BaseConfig {
    @Bean
    public Car car() {
            //very complex initialize routine for a car
        Car car = new Car();
        car.setmanufacture(getManufacture());
            System.out.println("complex car created");
        return car;
    }

    abstract Manufacture getManufacture();
}

@Configuration
CustomManu1 extends BaseConfig {
    Manufacture getManufacture() {
        //return custom manufacture
    }
}

@Configuration
CustomManu2 extends BaseConfig {
    Manufacture getManufacture() {
        //return custom manufacture
    }
}


@Configuration
@Import({CustomManu1.class, CustomManu2.class})
public class AppConfig {
}

Is that possible to inherit the @Bean and let spring create 2 Beans of type Car here?

Was it helpful?

Solution

Yes, public methods are inherited, so CustomManu1 and CustomManu2 will inherit the @Bean annotated method car().

and let spring create 2 Beans of type Car here?

This depends how you load your @Configuration classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top