Spring Boot detects 2 identical repository beans - spring

I am using Spring Boot with Spring Data JPA, there is only one #SpringBootApplication. And I have also a repository classes, for example:
package com.so;
public interface SORepository {
//methods
}
And impl
#Repository("qualifier")
#Transactional(readOnly = true)
public class SORepositoryImpl implements SORepository {
//methods
}
The proplem is, when I start the application, I get following error:
Parameter 0 of constructor in com.so.SomeComponent required a single bean, but 2 were found:
- qualifier: defined in file [path\to\SORepositoryImpl.class]
- soRepositoryImpl: defined in file [path\to\SORepositoryImpl.class]
So, as you see, somehow 2 beans of one repository class are created. How can I fix this?

You can use Spring Data JPA methods having created Proxy element and than inject it into public class SORepositoryImpl:
public interface Proxy() extends JpaRepository<Element, Long>{
Element saveElement (Element element); //ore other methods if you want}
And than:
#Repository
#Transactional(readOnly = true)
public class SORepositoryImpl implements SORepository {
#Autowired
private Proxy proxy;
//end realisation of methods from interface SORepository
}

Try taking the #Repository annotation off the SORepositoryImpl class
e.g.
#Transactional(readOnly = true)
public class SORepositoryImpl implements SORepository {
//methods
}
The error message is implying you have two beans, one named "qualifier" and one named "soRepositoryImpl", which is probably in a Config class.

I guess you should share your SomeComponent class supposing you have no extra configuration class/xml. My take is that you are injecting as 'soRepositoryImpl' there where you have defined as 'qualifier'. Having two options them. I would say to just remove the annotation parameter 'qualifier' and it should work.
Moreover, unless you want do specify an custom DAO implementation you can avoid #Repository at all (That's an annotation you use to make it injectable for your services). You can just create an interface extending Spring interface and define methods for queries.
For example:
public interface PersonRepository extends Repository<User, Long> {
List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
Then you can just inject it in your services/controller directly.
private final PersonRepository personRepository;
public PersonController(final PersonRepository personRepository) {
this.personRepository = personRepository;
}
check samples:
https://spring.io/guides/gs/accessing-data-jpa/
http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html

OK, I've found the issue.
I just couldn't understand, how Spring creates the second bean (soRepositoryImpl), because I've never told it, neither explicitly nor in config classes. But I figured out that the second bean us created during the instantiation of my another SORepository (which is in the different package com.another and which extends JpaRepository).
So, when Spring tries to resolve all dependencies of com.another.SORepository it somehow finds my com.so.SORepositoryImpl (which has nothing familiar with com.another.SORepository - not extending\implementing, not jpa stuff, only similar names!).
Well it seems like a Spring bug to me, because it doesn't check the real inheritance of dependent classes of repositories, only name + Impl (even in different package) suits for him.
The only thing that I should do is to rename `com.so.SORepositoryImpl and that it, no 2 beans anymore.
Thanks everyone for answers!

Related

Dependency injection through constructor vs property [duplicate]

So since I've been using Spring, if I were to write a service that had dependencies I would do the following:
#Component
public class SomeService {
#Autowired private SomeOtherService someOtherService;
}
I have now run across code that uses another convention to achieve the same goal
#Component
public class SomeService {
private final SomeOtherService someOtherService;
#Autowired
public SomeService(SomeOtherService someOtherService){
this.someOtherService = someOtherService;
}
}
Both of these methods will work, I understand that. But is there some advantage to using option B? To me, it creates more code in the class and unit test. (Having to write constructor and not being able to use #InjectMocks)
Is there something I'm missing? Is there anything else the autowired constructor does besides add code to the unit tests? Is this a more preferred way to do dependency injection?
Yes, option B (which is called constructor injection) is actually recommended over field injection, and has several advantages:
the dependencies are clearly identified. There is no way to forget one when testing, or instantiating the object in any other circumstance (like creating the bean instance explicitly in a config class)
the dependencies can be final, which helps with robustness and thread-safety
you don't need reflection to set the dependencies. InjectMocks is still usable, but not necessary. You can just create mocks by yourself and inject them by simply calling the constructor
See this blog post for a more detailed article, by one of the Spring contributors, Olivier Gierke.
I will explain you in simple words:
In Option(A), you are allowing anyone (in different class outside/inside the Spring container) to create an instance using default constructor (like new SomeService()), which is NOT good as you need SomeOtherService object (as a dependency) for your SomeService.
Is there anything else the autowired constructor does besides add code
to the unit tests? Is this a more preferred way to do dependency
injection?
Option(B) is preferred approach as it does NOT allow to create SomeService object without actually resolving the SomeOtherService dependency.
Please note, that since Spring 4.3 you don't even need an #Autowired on your constructor, so you can write your code in Java style rather than tying to Spring's annotations.
Your snippet would look like that:
#Component
public class SomeService {
private final SomeOtherService someOtherService;
public SomeService(SomeOtherService someOtherService){
this.someOtherService = someOtherService;
}
}
Good to know
If there is only one constructor call, there is no need to include an #Autowired annotation. Then you can use something like this:
#RestController
public class NiceController {
private final DataRepository repository;
public NiceController(ChapterRepository repository) {
this.repository = repository;
}
}
... example of Spring Data Repository injection.
Actually, In my experience, The second option is better. Without the need for #Autowired. In fact, it is wiser to create code that is not too tightly coupled with the framework (as good as Spring is). You want code that tries as much as possible to adopt a deferred decision-making approach. That is as much pojo as possible, so much such that the framework can be swapped out easily.
So I would advise you create a separate Config file and define your bean there, like this:
In SomeService.java file:
public class SomeService {
private final SomeOtherService someOtherService;
public SomeService(SomeOtherService someOtherService){
this.someOtherService = someOtherService;
}
}
In ServiceConfig.java file:
#Config
public class ServiceConfig {
#Bean
public SomeService someService(SomeOtherService someOtherService){
return new SomeService(someOtherService);
}
}
In fact, if you want to get deeply technical about it, there are thread safety questions (among other things) that arise with the use of Field Injection (#Autowired), depending on the size of the project obviously. Check this out to learn more on the advantages and disadvantages of Autowiring. Actually, the pivotal guys actually recommend that you use Constructor injection instead of Field Injection
I hope I won't be downgraded for expressing my opinion, but for me option A better reflects the power of Spring dependency injection, while in the option B you are coupling your class with your dependency, in fact you cannot instantiate an object without passing its dependencies from the constructor. Dependency Injection have been invented for avoid that by implementing Inversion of Control,so for me option B doesn't have any sense.
Autowired constructors provides a hook to add custom code before registering it in the spring container. Suppose SomeService class extends another class named SuperSomeService and it has some constructor which takes a name as its argument. In this case, Autowired constructor works fine. Also, if you have some other members to be initialized, you can do it in the constructor before returning the instance to spring container.
public class SuperSomeService {
private String name;
public SuperSomeService(String name) {
this.name = name;
}
}
#Component
public class SomeService extends SuperSomeService {
private final SomeOtherService someOtherService;
private Map<String, String> props = null;
#Autowired
public SomeService(SomeOtherService someOtherService){
SuperSomeService("SomeService")
this.someOtherService = someOtherService;
props = loadMap();
}
}
I prefer construction injection, just because I can mark my dependency as final which is not possible while injecting properties using property injection.
your dependencies should be final i.e not modified by program.
There are few cases when #Autowired is preferable.
One of them is circular dependency. Imagine the following scenario:
#Service
public class EmployeeService {
private final DepartmentService departmentService;
public EmployeeService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
}
and
#Service
public class DepartmentService {
private final EmployeeService employeeService;
public DepartmentService(EmployeeService employeeService) {
this.employeeService = employeeService;
}
}
Then Spring Bean Factory will throw circular dependency exception. This won't happen if you use #Autowired annotation in both beans. And this is understandable: the constructor injection happens at very early stage of Spring Bean initialization, in createBeanInstance method of Bean Factory, while #Autowired-based injection happens way later, on post processing stage and is done by AutowiredAnnotationBeanPostProcessor.
Circular dependency is quite common in complex Spring Context application, and it needs not to be just two beans referring one another, it could a complex chain of several beans.
Another use case, where #Autowired is very helpful, is self-injection.
#Service
public class EmployeeService {
#Autowired
private EmployeeService self;
}
This might be needed to invoke an advised method from within the same bean. Self-injection is also discussed here and here.
There is a way to inject the dependencies through constructor using #RequeiredArgsContructor annotation from Lombok
#RequiredArgsConstructor
#Service
class A {
private final B b // needs to be declared final to be injected
}
In this way you don't need to specify a constructor

Why spring data jpa unnecessary #Repository?

I've looked through various documents and questions about it, but I haven't been able to find a clear answer.
I don't know how an interface that extends JpaRepository can be registered as a bean, and why it doesn't need the #Repository annotation.
In Spring, an interface cannot register a bean with that type without an implementation.
So I tried experimenting like JpaRepository myself, but it didn't work.
// JpaRepository
#NoRepositoryBean
public interface WackRepository {
}
// SimpleJpaRepository
#Repository
public class WackRepositoryImpl implements WackRepository {
}
public interface HelloRepository extends WackRepository {
}
#RestController
#RequiredArgsConstructor
public class HelloController {
private final HelloRepository helloRepository;
}
Parameter 0 of constructor in com.example.demo.HelloController required a bean of type 'com.example.demo.HelloRepository' that could not be found
HelloController, of course, has no implementation, so it is not registered as a bean and throws an exception.
Spring Data detects extensions of the Repository Interface.
In Spring Boot the interfaces extending Repository are found automatically without Spring Boot or if the interfaces are not below the SpringBootApplication in the package hierarchy you have to configure the packages:
#EnableJpaRepositories("com.acme.repositories")
Source: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.create-instances

SpringBoot Bean dependency injection with annotation #Primary and #Secondary

I have a repository interface and two classes implementing it, one is cache repository and the other is MongoDB repository.
public interface Repository {}
#Primary
#Component
public class CacheRepo implement Repository {}
#Component
public class MongoDBRepo implement Repository {}
The ideal process for fetching an item would be to check if it exists in the cache using cache repo and if not, go with MongoDB repo, I have a #Primary on my CacheRepo class, and dependency inject Repository interface in my service, but how could I still use the same injected instance as MongoDBRepo if item not found in Cache? Is there something like #Secondary annotation?
What you are trying to implement is Repository Pattern
Here is a simple way to implement it
public interface MyRepository {
Optional<MyClass> findById(Long id);
}
Then you will have 3 implementations. This is where the logic lies.
#Repository
#Qualifier("db")
public interface MyDbRepository extends MyRepository, CrudRepository<MyClass, Long>{
}
#Component
#Qualifier("cache")
public class MyCacheRepository implements MyRepository {
public Optional<MyClass> findById(Long id){
return Optional.empty();
}
}
// This is the key
#Component
#Primary
public class MyDataSource implements MyRepository {
#Autowire
#Qualifier("db")
private MyRepository dbRepo;
#Autowire
#Qualifier("cache")
private MyRepository cacheRepo;
public Optional<MyClass> findById(Long id){
Optional<MyClass> myResponse = cacheRepo.findById(id);
if(myResponse.isPresent()){
return myResponse;
} else {
myResponse = dbRepo.findById(id);
if(myResponse.isPresent){
// Update your cache here
}
return myResponse;
}
}
}
I would suggest you take a look at #Qualifier. With it, you can specify which Bean you want to inject. For that, the best option is to define a component name for each bean as follows:
public interface Repository {}
#Component("cache")
public class CacheRepo implement Repository {}
#Component("mongodb")
public class MongoDBRepo implement Repository {}
Then, in another Spring-managed bean you can specify the implementation as follows:
#Autowired
#Qualifier("mongodb")
private Repository mongoRepo;
You can read more about it at https://www.baeldung.com/spring-qualifier-annotation.
I think you misunderstood the purpose of #Primary.
As the documentation says:
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.
You may use #Cacheble annotation on the MongoDBRepo's methods to do what you want and define a custom cache manager to use your CacheRepo
Here is a useful introduction to #Cacheble with some examples https://www.baeldung.com/spring-cache-tutorial

Spring Boot 2.5 and Spring Data: #NoRepositoryBean unexpected behaviour in multi-module project

I'm facing the following issue in a legacy code that I can't change. I have a multi module project which defines in the commons module a Spring Data interface as below:
package commons;
...
#NoRepositoryBean
public interface MyCustomRepository<P, I extends Number> extends JpaRepository<MyEntity, Integer>
{
MyEntity getOneAndCheck();
}
In another module I extend this interface as follows:
package data;
...
#Repository
public interface MyRepository extends MyCustomRepository<MyEntity, Integer>
{
...
}
So, the idea is that I don't want that Spring Data generates any implementation for the MyEntity getOneAndCheck() method 'cause it is implemented like this:
package data;
...
public class MyCustomRepositoryImpl implements MyCustomRepository
{
...
#Override
public MyEntity getOneAndCheck()
{
...
}
...
}
However, when I'm starting the application, I get the following exception:
...
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract MyEntity commons.MyCustomRepository.getOneAndCheck()! No property getOne found for type MyEntity!
...
So what it seems to happen is that Spring Data tries to generate a Query for the MyEntity getOneAndCheck() method, despite the #NoRepositoryBean annotation. This works as expected in the application I'm gonna migrate from Spring 3 with Spring Data to Spring Boot 2.5.
Not sure if the described behavior has anything to do with the fact that there are multiple Maven modules and that the repositories, the entities and the DTOs are in different modules. Not sure neither if there should be any difference between the way it runs currently with Spring and the one with Spring Boot. But the result is that all of the dozens of repositories in this legacy application are failing with the mentioned exception.
It might be important to mention that the main class needs to use annotations in order to tune the scanning:
#SpringBootApplication(scanBasePackages = "...")
#EnableJpaRepositories(basePackages={"...", "..."})
#EntityScan(basePackages= {"...", "..."})
public class MyApp
{
public static void main(String[] args)
{
SpringApplication.run(MyApp.class, args);
}
}
Not sure whether these annotations are supposed to change anything from the point of view of #NoRepositoryBean but the issue appeared as soon as I added this Spring Boot main class. It worked okay previously without Spring Boot.
Any suggestion please ?
Many thanks in advance.
Kind regards,
Seymour
There are two things that play together:
Spring Data's default custom implementation
Repository fragments
None of these apply because:
The default custom implementation follows the name of the actual repository. In your case, the implementation is named MyCustomRepositoryImpl whereas the repository name is MyRepository. Renaming the implementation to MyRepositoryImpl would address the issue
Since Spring Data 2.0, the repository detection considers interfaces defined at the repository level as fragment candidates where each interface can contribute a fragment implementation. While the implementation name follows the fragment interface name (MyCustomRepository -> MyCustomRepositoryImpl), only interfaces without #NoRepositoryBean are considered.
You have three options:
extracting your custom method into its own fragment interface and providing an implementation class that follows the fragment name:
interface MyCustomFragement {
MyEntity getOneAndCheck();
}
class MyCustomFragementImpl implements MyCustomFragement {
public MyEntity getOneAndCheck() {…}
}
public interface MyRepository extends MyCustomRepository<MyEntity, Integer>, MyCustomFragment {…}
Set the repositoryBaseClass via #EnableJpaRepositories(repositoryBaseClass = …) to a class that implements the custom method.
If you cannot change the existing code, you could implement a BeanPostProcessor to inspect and update the bean definition for the JpaRepositoryFactoryBean by updating repositoryFragments and adding the implementation yourself. This path is rather complex and requires the use of reflection since bean factory internals aren't exposed.

Where should #Service annotation be kept? Interface or Implementation?

I'm developing an application using Spring. I need to use the #Service annotation. I have ServiceI and ServiceImpl such that ServiceImpl implements ServiceI. I'm confused here as to where should I keep the #Service annotation.
Should I annotate the interface or the implementation with #Service? What are the differences between these two approaches?
I never put #Component (or #Service, ...) at an interface, because this make the interface useless. Let me explain why.
claim 1: If you have an interface then you want to use that interface for the injection point type.
claim 2: The purpose of an interface is that it define a contract that can been implemented by several implementations. On the other side you have your injection point (#Autowired). Having just one interface and only one class that implement it, is (IMHO) useless, and violates YAGNI.
fact: When you put:
#Component (or #Service, ...) at an interface,
have multiple classes that implements it,
at least two classes become Spring Beans, and
have an injection point that use the interface for type based injection,
then you will get and NoUniqueBeanDefinitionException
(or you have a very special configurations setup, with Environment, Profiles or Qualifiers ...)
Conclusion: If you use #Component (or #Service, ...) at an interface then you must violate at least one of the two clains. Therefore I think it is not useful (except some rare scenarios) to put #Component at interface level.
Spring-Data-JPA Repository interfaces are something complete different
Basically annotations like #Service, #Repository, #Component, etc. they all serve the same purpose:
auto-detection when using annotation-based configuration and classpath
scanning.
From my experience I am always using #Service annotation on the interfaces or abstract classes and annotations like #Component and #Repository for their implementation. #Component annotation I am using on those classes which serves basic purposes, simple Spring beans, nothing more. #Repository annotation I am using in the DAO layer, for e.g. if I have to communicate to the database, have some transactions, etc.
So I would suggest to annotate your interface with the #Service and other layers depending on the functionality.
I used #Component, #Service, #Controller and #Repository annotations only on the implementation classes and not on the interface. But #Autowired annotation with Interfaces still worked for me. If there's only one implementation of your interface Spring component scan automatically finds it with just #Autowired annotation. In case you have multiple implementations, you will need to use the #Qualifier annotation along with #Autowired to inject the correct implementation at the injection point.
1. #Service on Interfaces
#Service
public interface AuthenticationService {
boolean authenticate(String username, String password);
}
Normally, that's fine, but there's a drawback. By putting Spring's #Service on interfaces, we create an extra dependency and couple our interfaces with an outside library.
Next, to test the autodetection of our new service beans, let's create an implementation of our AuthenticationService:
public class InMemoryAuthenticationService implements AuthenticationService {
#Override
public boolean authenticate(String username, String password) {
//...
}
}
We should pay attention that our new implementation, InMemoryAuthenticationService, doesn't have the #Service annotation on it. We left #Service only on the interface, AuthenticationService.
So, let's run our Spring context with the help of a basic Spring Boot setup:
#SpringBootApplication
public class AuthApplication {
#Autowired
private AuthenticationService authService;
public static void main(String[] args) {
SpringApplication.run(AuthApplication.class, args);
}
}
When we run our app, we may get the infamous NoSuchBeanDefinitionException, and the Spring context fails to start.
Therefore, placing #Service on interfaces isn't enough for the auto-detection of Spring components.
2. #Service on Abstract Classes
Using the #Service annotation on abstract classes isn't common.
We'll start by defining an abstract class from scratch and putting the #Service annotation on it:
#Service
public abstract class AbstractAuthenticationService {
public boolean authenticate(String username, String password) {
return false;
}
}
Next, we extend AbstractAuthenticationService to create a concrete implementation without annotating it:
public class LdapAuthenticationService extends AbstractAuthenticationService {
#Override
public boolean authenticate(String username, String password) {
//...
}
}
Accordingly, we also update our AuthApplication, to inject the new service class:
#SpringBootApplication
public class AuthApplication {
#Autowired
private AbstractAuthenticationService authService;
public static void main(String[] args) {
SpringApplication.run(AuthApplication.class, args);
}
}
After we run our AuthApplication, the Spring context doesn't start. It ends up with the same NoSuchBeanDefinitionException exception again.
So, using #Service annotation on abstract classes doesn't have any effect in Spring.
3. #Service on Concrete Classes
Contrary to what we've seen above, it's quite a common practice to annotate the implementation classes instead of abstract classes or interfaces.
In this way, our goal is mostly to tell Spring this class is going to be a #Component and mark it with a special stereotype, which is #Service in our case.
Therefore, Spring will autodetect those classes from the classpath and automatically define them as managed beans.
So, let's put #Service on our concrete service classes this time around. We'll have one class that implements our interface and a second that extends the abstract class that we defined previously:
#Service
public class InMemoryAuthenticationService implements AuthenticationService {
#Override
public boolean authenticate(String username, String password) {
//...
}
}
#Service
public class LdapAuthenticationService extends AbstractAuthenticationService {
#Override
public boolean authenticate(String username, String password) {
//...
}
}
We should take notice here that our AbstractAuthenticationService doesn't implement the AuthenticationService here. Hence, we can test them independently.
Finally, we add both of our service classes into the AuthApplication and give it a try:
#SpringBootApplication
public class AuthApplication {
#Autowired
private AuthenticationService inMemoryAuthService;
#Autowired
private AbstractAuthenticationService ldapAuthService;
public static void main(String[] args) {
SpringApplication.run(AuthApplication.class, args);
}
}
Our final test gives us a successful result, and the Spring context boots up with no exceptions. Both of the services are automatically registered as beans.
You might have a look at this page for the other explanations.
Pros of putting annotation on #Service is that it gives a hint that it is a service. I don't know if any implementing class will by default inherit this annoation.
Con side is that you are coupling your interface with a specific framework i.e. Spring, by using spring specific annotation.
As interfaces are supposed to be decoupled from implementation, I would not suggest using any framework specific Annotations or object part of your interface.
I would put #Service on your class but put the name of the interface as a parameter to the annotation e.g.
interface ServiceOne {}
#Service("ServiceOne")
class ServiceOneImpl implements ServiceOne{}
By doing that you get all the benefits and can still inject the interface but get the class
#Autowired
private ServiceOne serviceOne;
So your interface is not tied to spring framework and you can change the class at any time and not have to update all your injection points.
So if I wanted to change the implementation class I could just annotate the new class and remove from the first but that's all that is required to be changed. If you inject the class you could have a lot of work when ever you want to change the impl class.
One benefit of spring is to easily switch Service (or other) implementation.
For this, you need to annotate on the interface and declare variable like this :
#Autowired
private MyInterface myVariable;
and not :
#Autowired
private MyClassImplementationWhichImplementsMyInterface myVariable;
Like the first case, you can activate which implementation to inject from the moment it is unique (only one class implements the interface).
In the second case, you need to refactor all your code (the new class implementation has another name).
As a consequence, the annotation needs to be on the interface as much as possible. Furthermore, JDK proxies are well suited for this : they are created and instantiated at application startup because runtime type is known by advance, contrary to CGlib proxies.
interface MyService {}
#Service
class MyServiceImpl implements MyService{}
#Autowired
private MyService myService;
My testing result on spring-boot 2.7.4 is:
Adding #Service ONLY to interface doesn't create spring bean named MyService. It will error on Autowired.
#Service will need to be added to implementation class to create bean com.*.service.impl.MyServiceImpl $$EnhancerBySpringCGLIB$$9140ae19 Spring will wire it to private MyService myService;
There are 5 annotations which could be used for making spring beans. List in below of answers.
Do you really need an interface? If you are going to have one implementation for each service interface, just avoid it, use only class. Of course, if you don't have RMI or when interface proxy is required.
#Repository - use for injecting your dao layer classes.
#Service - use for injecting your service layer classes. In service layer also you might need to use #Transactional annotation for db transaction management.
#Controller - use for your frontend layer controllers, such as JSF managed beans injecting as spring beans.
#RestController - use for spring rest controllers, this would help you to avoid every time to put #ResponseBody and #RequestBody annotations in your rest methods.
#Component - use it in any other case when you need to Inject spring bean which is not controller, service, or dao class
To put it simply:
#Service is a Stereotype annotation for the service layer.
#Repos­itory is a Stereotype annotation for the persis­tence layer.
#Component is a generic stereotype annotation used to tell Spring to create an instance of the object in the Appl­ication Context. It's possible to
define any name for the instance, the default is the class name as camel case.

Resources