0

There is a lot of boiler plate code when developing Java EE apps.

One of the places is the need for interfaces for Services. Is it possible to skip the interface part.

I am asking since the @Service annotation is used on a class, and not the interface.

@Repository is for instance used on the interface.

What would be the implications of not using an interface for a service? Will @Transaction and other annotations work as expected?

I do understand Grails and other Frameworks don't have the need for interfaces so although you'd say it is good for business logic and what not, I understand this aspect but it is not always necessary and can be added afterwards, when there is a need.

3
  • No, my application is pretty much empty, and my concern is that many other things such as @Transaction and such, which I am unsure of how to test, will work, not knowing about it.. Commented Aug 1, 2014 at 11:56
  • 1
    If your writing a simple project and you don't foresee dropping other implementations of your service a single concrete class will suffice. Commented Aug 1, 2014 at 12:06
  • @Bart Thanks, I imagine it is pretty easy to add an interface later on, when needed than do it in advance. Commented Aug 1, 2014 at 12:11

1 Answer 1

1

There's no real danger in not using an interface for your service. Not using one just means your code is deeply tied to the service implementation. In practice, I don't create an interface for my services. I just annotate my concrete class with Service because it's rare that I need a generic service class that has several implementations. A repository on the other hand, you will often see an interface annotated with Repository because Spring Data uses AOP to create an instance of your repository at runtime. What you could do if you want to create an interface is use java bean config. Create a bean method that instantiates a concrete service class, the return type could be the interface your service class implements. That way your concrete implementation is only tied to the initial bean config and you can change it out pretty easily.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I am using repositories as well, unfortunately I can't get away from the interfaces ( including the custom ones ) there I believe. Annotations for repositories is not working either, so I am using the <jpa:repositories for setting it up. Are you suggesting a base service class / or component in which I autowire all my services, any danger or are they always singletons?
Have a look at the docs here docs.spring.io/spring/docs/4.0.6.RELEASE/… the first example AppConfig defines a MyService bean where MyService would be an interface, and MyServiceImpl would be the concrete implementation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.