简体   繁体   中英

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. In my project I have a class MyObj, which uses ExtObj. How can I configure spring 3 to inject ExtObj in MyObj?

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

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. 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). Eg. if ExtObj has a constructor taking a String you can define the bean this way:

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

To define MyObj you can use constructor injection:

<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 . If you use constructor injection MyObj needs to have a constructor taking an instance of the ExtObj class.

Of course you can inject a 3rd party library, as long as it has constructors that Spring can access.

You can use either XML or annotations - your choice.

You need to ask Spring to instantiate the instance(s) of the library class and then inject that into your objects that need them.

You do this every time you create a Spring data source that uses a JDBC driver. That's a 3rd party library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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