Spring Inheritance - Annotation

2020-07-11 06:16发布

I came across this link which explains how a bean can be inherited. Assuming that HelloWorld class in this example is exposed as a bean using @Component annotation , how can create another bean which inherits this bean? Can I use extends to inherit HelloWorld bean and add @Component to the new class in order to extend the existing bean expose it as a new bean with additional features?

标签: java spring
1条回答
淡お忘
2楼-- · 2020-07-11 06:54

First you make your abstract configuration, which is achieved by not marking it as @Configuration, like this:

// notice there is no annotation here
public class ParentConfig {

    @Bean
    public ParentBean parentBean() {
        return new ParentBean();
    }

}

An then you extend it, like this:

@Configuration
public class ChildConfig extends ParentConfig {

    @Bean
    public ChildBean childBean() {
        return new ChildBean();
    }

}

The result will be exactly the same as if you did this:

@Configuration
public class FullConfig {

    @Bean
    public ParentBean parentBean() {
        return new ParentBean();
    }

    @Bean
    public ChildBean childBean() {
        return new ChildBean();
    }

}

Edit: answer to the follow-up question in the comment.

If Spring picks up both classes, parent and child, there will be problems with duplicated beans, so you cannot extend it directly. Even if you override methods, the beans from the super-class will also be instantiated by the ParentConfig.

Since your parent class is already compiled, you have 2 options:

  1. Talk to the author of the parent class and kindly ask him to change it.

  2. Change the @ComponentScan packages.

To clarify on solution 2:

If the parent class is in the package com.parent.ParentConfig and the child class is the package com.child.ChildConfig, you can configure the component scanning so that only classes under com.child get picked up.

You can specify the component scanning packages using the @ComponentScan("com.child") annotation on your main configuration file (think application class).

查看更多
登录 后发表回答