@Bean @Configuration可以继承吗?

时间:2014-04-09 07:21:08

标签: java spring autowired

在spring中可以从抽象类继承,并让实现自动创建任何@Bean注释方法的实例吗?

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 {
}

是否可以继承@Bean并让spring在这里创建2个Car类型的Bean?

1 个答案:

答案 0 :(得分:1)

是的,公共方法是继承的,因此CustomManu1CustomManu2将继承@Bean带注释的方法car()

  

让春天在这里创造出两种类型的Beans豆?

这取决于您加载@Configuration类的方式。