What is the bean ID of spring bean implements an i

2019-07-21 08:17发布

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)}">

2条回答
Luminary・发光体
2楼-- · 2019-07-21 08:57
for (String name : context.getBeanDefinitionNames()){
    System.out.println(name);
}

This test revealed some interesting outcomes.

service beans

Service beans are named after the concrete class name regardless of the interface.

@Service
public class ProfileServiceImpl implements ProfileService

ie. profileServiceImpl in the above question.

Repository beans

Further Repository beans are something more interesting. Below is my crud repository interface without any annotations.

public interface UserRepository extends CrudRepository<User, Long>, DatatablesCriteriasRepository<User>{

And I created an implementation of the UserRepositoryImpl for the DatatablesCriteriasRepository as below without any annotations.

public class UserRepositoryImpl implements DatatablesCriteriasRepository<User>

these two included two beans with IDs userRepository userRepositoryImpl respectively.

查看更多
闹够了就滚
3楼-- · 2019-07-21 09:00

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 of UserRepositoryImpl extends DatatablesCriteriasRepository than Spring wouldn't have created the userRepository bean. Addtionally, if you add @NoRepositoryBean annotation to the UserRepository interface, that will suppress the creation of the userRepository bean.

However, UserRepositoryImpl really should be implementing UserRepository. If it really is intended to extend DatatablesCriteriasRepository, than it should be nameed DatatablesCriteriasRepositoryImpl. Having UserRepsitoryImpl extend DatatablesCriteriasRepository is indication of a problem in the design.

查看更多
登录 后发表回答