简体   繁体   English

自动连接抽象类中的不同bean

[英]autowire distinct beans in abstract class

I have the following problem: 我有以下问题:

Suppose I have an abstract class lets say: 假设我有一个抽象类,可以这样说:

public abstract class AbstractHbmDao implements SomeInterface {
    @Autowired
    protected SessionFactory sessionFactory;
    //getters & setters

    //interface stuff
}

Then several implementations of SomeInterface -> A_Interface , B_Interface , etc. This is ok if I use the same SessionFactory for every implementation. 然后是SomeInterface > A_InterfaceB_Interface等的几种实现。如果我对每个实现都使用相同的SessionFactory ,则可以。

The problem is I want to use distinct SessionFactory for distinct group of of implementations and I do not want to specify with the @Qualifier . 问题是我想对不同的实现组使用不同的SessionFactory ,并且我不想使用@Qualifier指定。 This would be less flexible to define these groups since I would need to change the code. 定义这些组的灵活性较差,因为我需要更改代码。 Also by putting the SessionFactory in the abstract class if would be impossible to specify with the @Qualifier annotation. 另外,如果不可能用@Qualifier注释指定,​​则将SessionFactory放在抽象类中。

Is there a way to do it in the xml bean definition ? 有没有办法在xml bean定义中做到这一点? I tried by declaring two SessionFactory beans and for each of then ref the corresponding class, but this would still return NoUniqueBeanDefinitionException . 我通过声明两个SessionFactory bean进行尝试,然后为每个Bean引用相应的类,但这仍将返回NoUniqueBeanDefinitionException

Field injection is fragile all on its own, and constructor injection should be preferred whenever possible. 字段注入本身就很脆弱,应该尽可能使用构造函数注入。 That's the clean solution here: Make an abstract ( protected ) constructor on your base class that takes your bean as an argument, and use @Qualifier on the subclass constructors. 这是干净的解决方案:在基类上创建一个抽象的( protected )构造函数(将bean作为参数),并在子类构造函数上使用@Qualifier

An alternative approach that uses Field injection is to not autowire the field in the base class, but instead creating an abstract method to get the SessionFactory and autowire the field in the subclasses. 使用字段注入的另一种方法是不自动连接基类中的字段,而是创建一个抽象方法来获取SessionFactory并自动连接子类中的字段。

public abstract class AbstractHbmDao implements SomeInterface {
    protected abstract SessionFactory getSessionFactory();
}

And in subclasses implement this method: 并在子类中实现此方法:

public MyDao extends AbstractHbmDao {
    @Autowired
    @Qualifier("my-qualifier")  // add qualifier as needed now
    private SessionFactory sessionFactory;

    protected SessionFactory getSessionFactory() { return sessionFactory; }
}

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

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