简体   繁体   English

自动装配到不同的bean

[英]Autowiring to different beans

I have a core module with a class that contains: 我有一个核心模块,其中包含一个类:

@Autowired
private BaseDao dao;

and few implementations of BaseDao interface: BaseDao接口的实现很少:

class JdbcBaseDaoImpl implements BaseDao {...}
class HibernateBaseDaoImpl implements BaseDao {...}

And few modules which use that class from the core module (using maven). 并且很少有模块使用核心模块中的那个类(使用maven)。 But in the first module, I want to use JdbcBaseDaoImpl implementation in that field of core module and in the second module, to use HibernateBaseDaoImpl implementation. 但是在第一个模块中,我想在核心模块的那个领域和第二个模块中使用JdbcBaseDaoImpl实现,以使用HibernateBaseDaoImpl实现。

How to do that? 怎么做? In other words, how to use class in core module with 换句话说,如何在核心模块中使用类

@Autowired
@Qualifier("jdbcBaseDaoImpl")
private BaseDao dao;

in first module and 在第一个模块和

@Autowired
@Qualifier("hibernateBaseDaoImpl")
private BaseDao dao;

in second module? 在第二个模块?

The annotation is @Qualifier("<name>") . 注释是@Qualifier("<name>") See this for more details. 有关详细信息,请参阅

BTW, the Java EE equivalent of this is @Resource(name="<name>") . 顺便说一下,Java EE相当于@Resource(name="<name>")

If these modules are going to run in the same process space, then it is not possible to conditionally inject different implementations into the same variable in core module based on the code path. 如果这些模块将在相同的进程空间中运行,则不可能基于代码路径有条件地将不同的实现注入到核心模块中的相同变量中。 You can instead push the BaseDao reference into the dependent modules, inject the appropriate one for each and pass it as a reference to the core module's method that need it. 您可以将BaseDao引用推送到依赖模块,为每个模块注入适当的模块,并将其作为对需要它的核心模块方法的引用传递。

If these modules are going to run in different process space, then you can configure the appropriate implementation for each module, in the process specific spring configuration file (This we do for separating the implementations for production and unit test stages). 如果这些模块将在不同的进程空间中运行,那么您可以在特定于进程的spring配置文件中为每个模块配置适当的实现(我们这样做是为了分离生产和单元测试阶段的实现)。

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

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