简体   繁体   English

春天3:从库注入依赖项?

[英]spring 3: inject a dependency from a library?

I am developing a project and using 3rd party libraries. 我正在开发一个项目,并使用第三方库。 Let's say I use a library which gives me the object ExtObj. 假设我使用的库为我提供了对象ExtObj。 In my project I have a class MyObj, which uses ExtObj. 在我的项目中,我有一个MyObj类,它使用ExtObj。 How can I configure spring 3 to inject ExtObj in MyObj? 如何配置spring 3在MyObj中注入ExtObj?

I tried to research the topic on the internet, but I didn't find a straight answer. 我试图在互联网上研究该主题,但没有找到直接的答案。 I would like to use xml configuration and maybe (?) @Autowired , not @EJB or @Inject 我想使用xml配置,也许使用(?)@ @Autowired ,而不是@EJB@Inject

Thanks in advance! 提前致谢!

UPDATE my guess was: 更新我的猜测是:

<bean id="myObj" value="me.MyObj">
  <property name="extObj" value=" ... ??? ...">
</bean>

So, I don't know what I should put into value. 所以,我不知道我该怎么做。 I guess that's where the reference to the external object goes. 我想这就是对外部对象的引用。 But spring can only reference objects that have been already defined/configured in spring. 但是spring只能引用已经在spring中定义/配置的对象。 So: 所以:

<bean id="extObj" value="ext.lib.ExtObj">
<bean id="myObj" value="me.MyObj">
  <property name="extObj" value="extObj">
</bean>

Is that configuration right? 该配置正确吗?

First you need to define a bean for your ExtObj in your application context (an xml file or a @Configuration class). 首先,您需要在应用程序上下文(xml文件或@Configuration类)中为ExtObj定义一个bean。 Eg. 例如。 if ExtObj has a constructor taking a String you can define the bean this way: 如果ExtObj具有带String的构造函数,则可以通过以下方式定义bean:

<bean id="extObj" class="ext.lib.ExtObj">
    <constructor-arg value="SomeString"/>
</bean>

To define MyObj you can use constructor injection: 要定义MyObj ,可以使用构造函数注入:

<bean id="myObj" class="me.MyObj">
    <constructor-arg ref="extObj"/>
</bean>

or setter injection: 或二传手注射:

<bean name="myObj" class="me.MyObj">
    <property name="extObj" ref="extObj"/>
</beans>

If you use setter injection then MyObj needs to have a setter setExtObj . 如果使用setter注入,则MyObj需要具有setter setExtObj If you use constructor injection MyObj needs to have a constructor taking an instance of the ExtObj class. 如果使用构造函数注入,则MyObj需要具有一个使用ExtObj类的实例的构造函数。

Of course you can inject a 3rd party library, as long as it has constructors that Spring can access. 当然,您可以注入第3方库,只要它具有Spring可以访问的构造函数即可。

You can use either XML or annotations - your choice. 您可以选择使用XML或注释。

You need to ask Spring to instantiate the instance(s) of the library class and then inject that into your objects that need them. 您需要让Spring实例化库类的实例,然后将其注入需要它们的对象中。

You do this every time you create a Spring data source that uses a JDBC driver. 每次创建使用JDBC驱动程序的Spring数据源时,都要执行此操作。 That's a 3rd party library. 那是第三方图书馆。

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

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