I was just wondering, why there is no interface for a Spring Bean or for a EJB Bean (or for an OSGi service)? I know that there is no need for this because frameworks can use reflection API for calling methods but wouldn’t it be less erroneus if interfaces were used instead?
For example, why there is no interface for OSGi component which would look like this:
interface OSGIComponent {
void activate(BundleContext context);
...
}
In the case of Spring, you don’t have to implement a Spring-specific interface to be able to use Spring with your code. This is actually seen as an advantage: it prevents your code being tied to Spring, therefore making it more portable.
That’s not to say that you can’t implement Spring-specific interfaces. One example that springs to mind (no pun intended) is
InitializingBean; this defines a method,afterPropertiesSet(), which gets called (as the name suggests) after Spring has instantiated your bean and set all of its properties.So there are often framework-specific interfaces and classes that you can use; you have to balance keeping your code portable with making use of the useful stuff that frameworks provide.
You gave the example of an OSGi component that might implement an
OSGIComponentinterface. Spring does in fact have an interface that your class can implement to be passed a reference to the containing Spring context:ApplicationContextAware. Typically, though, you don’t need to make use of these framework-specific interfaces. Your code is generally easier to understand if it just focuses on the actual business logic, rather than details of how the framework is instantiating objects, wiring objects together, and so on.