How to use Spring on a class situated in a library?

Issue

Although I’m comfortable with other DI especially MacWire, I need for a project to deal with Spring.

I’m trying to integrate an external library of service that I am developing to a main application that uses Spring to instantiate its services. I’m wondering how can I do such that the code in the Library is treated the same as the code in the source with respect to Spring?

That is instantiating class in my library, from with within the main source of the project using Spring. Do I just give the path of the package to scan the bean from?

Solution

Spring configuration file help you to achieve DI. What I understand from question is, you are looking for a way to use Spring capabilities to instantiate a class. The way to instantiate bean remain same for external service or your own library code.

Say if you have classes like:

//External Library class
package com.test;
public class HelloWorld{
   ...
}

// Your class
package com.abc;
import com.test.HelloWorld;

public class MyClass{
   HelloWorld obj;
   ...
}   

Spring XML configuration file will look like,

    <beans>
       <!-- External library class -->
       <bean id="helloWorld" class="com.test.HelloWorld" />
        <!-- Your class -->
       <bean id="myClass" class="com.abc.MyClass">
           <property name="obj" ref="helloWorld"/>
       </bean>
    </beans>

I recommend you to refer ‘Spring Dependency Injection’ in Spring documentation..

Answered By – Gaurang Patel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published