简体   繁体   English

如何使用spring注释注入父类属性

[英]how to inject parent class property with spring annotation

parent class is like this: 父类是这样的:

public class BaseDAO{
    private DBRoute defaultDB;

    public DBRoute getDefaultDB()
    {
        return this.defaultDB;
    }

    public void setDefaultDB(DBRoute defaultDB)
    {
        this.defaultDB = defaultDB;
    }
}

I have create beans like below: 我创建了如下的bean:

<bean id="adsConfigDB" class="net.flyingfat.common.dbroute.config.DBRoute">
    <constructor-arg value="adsConfig" />
</bean>

<bean id="adsBizDateDB" class="net.flyingfat.common.dbroute.config.DBRoute">
    <constructor-arg value="adsBizDate" />
</bean>

I want to inject superclass property defaultDB in subclass through byName, not byType, which is in subclass inject defaultDB using adsConfigDB or adsBizDateDB . 我想通过byName注入超类属性defaultDB ,而不是byType,它使用adsConfigDBadsBizDateDB在子类中注入defaultDB Is there any way to do this with spring annotations? 有没有办法用spring注释做到这一点? I already tried Autowired or Resource with constructor which doesn't work. 我已经尝试过Autowired或Resource with constructor,但是它不起作用。 By the way, I already know this can be done using XML. 顺便说一句,我已经知道这可以使用XML完成。

@Qualifier annotation – This annotation is used to avoid conflicts in bean mapping and we need to provide the bean name that will be used for autowiring. @Qualifier注释 - 此注释用于避免bean映射中的冲突,我们需要提供将用于自动装配的bean名称。 This way we can avoid issues where multiple beans are defined for same type. 这样我们就可以避免为同一类型定义多个bean的问题。 This annotation usually works with the @Autowired annotation. 此注释通常与@Autowired注释一起使用。 For constructors with multiple arguments, we can use this annotation with the argument names in the method. 对于具有多个参数的构造函数,我们可以将此注释与方法中的参数名称一起使用。

Your code will be like this.. 你的代码就像这样..

@Autowired
@Qualifier("adsConfig")
private DBRoute defaultDB;

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

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