简体   繁体   English

Java Spring-将带有注释的参数注入超类

[英]Java Spring - Inject a parameter into a superclass with annotations

I have a superclass that needs the subclass to provide the implementation of the interface that the superclass runs against. 我有一个超类,它需要子类来提供超类运行所针对的接口的实现。

We use Spring and DI so we can't just create the implementation with new. 我们使用Spring和DI,所以我们不能仅仅使用new创建实现。

The subclass will know which bean to provide only after Spring is initialized so using a super constructor won't work. 子类仅在初始化Spring之后才知道要提供哪个bean,因此使用超级构造函数将不起作用。

I also don't want to use q @PostConstruct setup method in the subclass as that requires the subclass developer to know how to set up the superclass. 我也不想在子类中使用q @PostConstruct设置方法,因为这需要子类开发人员知道如何设置超类。

I want the superclass to demand the subclass to provide the reference to the implementing bean so that it can setup its member: 我希望超类要求子类提供对实现Bean的引用,以便它可以设置其成员:


The superclass uses the UrlBuilder Interface: 超类使用UrlBuilder接口:

public class JsonConnection{

    private UrlBuilder urlBuilder;
}

the subclass provides the implementation ( UrlBuilderFacebook ) via dependency injection. 子类通过依赖项注入提供实现( UrlBuilderFacebook )。

@Component
public class FacebookJsonConnection extends JsonConnection {

    @Inject
    private UrlBuilder urlBuilderFacebook;    
}

the superclass can be abstract or a component, it doesn't matter. 超类可以是抽象的也可以是组件,没关系。 What matters is that I want to be able to create lightweight subclasses that provide the UrlBuilder to the superclass and @Inject them where needed. 重要的是,我希望能够创建将UrlBuilder提供给超类的轻量级子类,并在需要时@Inject

@Inject
private JsonConnection facebookJsonConnection;

or 要么

@Inject
private JsonConnection redmineJsonConnection;

Also I don't want the superclass to know anything about which subclass is using it. 我也不希望超类对正在使用它的子类一无所知。

If urlBuilder is required for JsonConnection you can pass it as a constuctor argument and use constructor injection: 如果urlBuilder需要JsonConnection ,则可以将其作为构造函数参数传递并使用构造函数注入:

public class JsonConnection{
    private UrlBuilder urlBuilder;

    public JsonConnection(UrlBuilder urlBuilder) {
        this.urlBuilder = urlBuilder;
    }
} 

@Component  
public class FacebookJsonConnection extends JsonConnection {
    private UrlBuilder urlBuilderFacebook;
    @Inject
    public FacebookJsonConnection(UrlBuilder urlBuilderFacebook) {
        super(urlBuilderFacebook);
        this.urlBuilderFacebook = urlBuilderFacebook;
    }
}  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM