In the official website of Spring framework, there's an example which shows how Spring decouple a class from an interface, or better to say, an implementation if an interface.
Here's the code:
Interface:
package hello;
public interface MessageService {
String getMessage();
}
Component Class:
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MessagePrinter {
final private MessageService service;
@Autowired
public MessagePrinter(MessageService service) {
this.service = service;
}
public void printMessage() {
System.out.println(this.service.getMessage());
}
}
Application:
package hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
@Configuration
@ComponentScan
public class Application {
@Bean
MessageService mockMessageService() {
return new MessageService() {
public String getMessage() {
return "Hello World!";
}
};
}
public static void main(String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(Application.class);
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.printMessage();
}
}
What I currently understand about dependency injection is that when a class named A
need another class named B
for processing what ever it must do, B
is a dependency and A
is dependent. If B
is an interface, then A
is dependent on some implementation of B
.
So, in the above code, how MessagePrinter
is decoupled from MessageService
implementation ?
we still have to implement MessageService
, If we don't implement it, can MessagePrinter
function properly?
Regards