Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I know how constructor and setter injection works in spring.

Normally I use interfaces instead of classes to inject beans using setter and I consider it as interface injection, but in case of constructor we also use interfaces (I am confused). In following example I use JobProcessor interface instead of JobProcessorImpl class.

public class JobScheduler {
    // JobProcessor interface
    private JobProcessor jobProcessor;
    // Dependecy injection
    public void setJobProcessor(JobProcessor jobProcessor){
        this.jobProcessor = jobProcessor;
    }
}

I tried to find a solution by googling but there are different opinions by writers. Even some people says that spring doesn't support interface injection in their blogs/statements.

Can someone help me by example?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

In interface injection, the setter method is provided by an interface that is implemented by the bean in which we are going to inject the dependency. Example:

package some.package;
public class Car implements EngineMountable {
    private Engine engine;
    @Override //dependency injection
    public void mount(Engine engine){
        this.engine = engine;
    }
}

public interface EngineMountable {
    void mount(Engine engine);
}

The same is working for me in spring by applying following configuration:

<bean name="car" class="some.package.Car">
    <property name="mount" ref="engineObject" />
</bean>

In some sites people says that spring does not supports interface injection, but for me the above example works in spring. As per me : spring supports interface injection.

Reference : Martin Fowler : Interface Injection

share|improve this answer
    
I don't see the difference between this and "setter injection", other than that the "setter" method is specified in an interface here. Fundamentally, the two are basically identical. Am I wrong? Could you clarify the answer by contrasting this with "setter injection"? –  Jez Apr 3 at 9:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.