Spring继承 - 注释 [英] Spring Inheritance - Annotation

查看:135
本文介绍了Spring继承 - 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个链接,它解释了如何继承bean。假设此示例中的HelloWorld类使用@Component注释作为bean公开,如何创建另一个继承此bean的bean?我可以使用extends来继承HelloWorld bean并将@Component添加到新类中以扩展现有bean,将其公开为具有附加功能的新bean吗?

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?

推荐答案

首先进行抽象配置,这是通过将其标记为 @Configuration ,像这样:

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.

如果Spring选择了父母和孩子这两个班级,重复的bean会有问题,所以你不能直接扩展它。即使你重写方法,超类中的bean也将由 ParentConfig 实例化。

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.

您的父类已经编译,您有2个选项:


  1. 与作者联系家长班并请他改变它。

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

更改 @ComponentScan 包裹。

澄清解决方案2:

如果父类是在包 com.parent.ParentConfig 中,子类是包 com.child.ChildConfig ,你可以配置组件扫描,以便只有 <$ strong> <$ strong> <$ strong> com.child 下的类才被选中。

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.

您可以在主配置文件(想想应用程序类)上使用 @ComponentScan(com.child)注释指定组件扫描包。

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

这篇关于Spring继承 - 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆