When the bean is createt for a class as MyBean
the bean id is myBean
but what will be the bean ID if I create the service bean from an interface like below?
@Service
public class ProfileServiceImpl implements ProfileService
When I try to access the bean as @profileService
thymeleaf gives the below error.
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'profileService' is defined
All this time I'm using this bean by autowiring
to the controller. But at the moment I need to access this from the thymeleaf
.
My thymeleaf code segment
<div th:unless="${@profileService.isMe(user)}">
This test revealed some interesting outcomes.
service beans
Service beans are named after the concrete class name regardless of the interface.
ie.
profileServiceImpl
in the above question.Repository beans
Further Repository beans are something more interesting. Below is my crud repository interface without any annotations.
And I created an implementation of the
UserRepositoryImpl
for theDatatablesCriteriasRepository
as below without any annotations.these two included two beans with IDs
userRepository
userRepositoryImpl
respectively.When Spring creates a Bean Definition from a @Service or @Component annotation, it will by default create an id for the bean by lowercasing the first letter of the Class Name. If you want to override that the behavior, you can provide an alternative id in the annotation, eg. @Service("profileService").
Regarding what you are experiencing with the Repository - by default Spring looks for a custom implementation of a Repository by appending "Impl" to the Repository Interface name. If it finds it, it will not create a default implementation. So, if you had
UserRepositoryImpl extends UserRepository
instead ofUserRepositoryImpl extends DatatablesCriteriasRepository
than Spring wouldn't have created theuserRepository
bean. Addtionally, if you add@NoRepositoryBean
annotation to theUserRepository
interface, that will suppress the creation of theuserRepository
bean.However,
UserRepositoryImpl
really should be implementingUserRepository
. If it really is intended to extendDatatablesCriteriasRepository
, than it should be nameedDatatablesCriteriasRepositoryImpl
. HavingUserRepsitoryImpl
extendDatatablesCriteriasRepository
is indication of a problem in the design.