I want to use both Redis and Mongo with repository manner (I do not want to use spring cache annotations but repository methods).
I annotate the main class with the following annotations.
#EnableMongoRepositories(basePackageClass = PersistencyRepository.class)
#EnableRedisRepositories(basePackageClass = CacheRepository.class)
#SpringBootApplication
Repos
public interface PersistencyRepository extends CrudRepository<Store, String> {}
public interface CacheRepository extends MongoRepository<Store, String> {}
Now, I am getting the following error.
The bean "cacheRepository" defined in com.repository.CacheRepository defined in #EnableMongoRepositories declared on StoreApplication, could not be registered. A bean with that name has already been defined in com.repository.CacheRepository defined in #EnableRedisRepositories declared on StoreApplication and overriding is disabled.
How can I use repos of differenet databases (mongo, redis)?
You extended the wrong repository interface (MongoRepository) on CacheRepository try extending CrudRepository instead.
Also, your mongo and redis entities should be separated to different packages, usually I just went with com.my.company.entity.mongo and com.my.company.entity.redis for each.
After that, you need to update those Configuration annotations. A better package design, instead of putting all annotations on Main is putting them on a separate package, then putting those annotations there. This has an added benefit of clearly splitting each configurations for what they actually do
for example:
package com.your.company.configuration;
import com.your.company.configuration.properties.ApplicationProperties;
import com.your.company.entity.mongo.BaseDocument;
import com.your.company.entity.postgres.BaseEntity;
import com.your.company.entity.redis.BaseHash;
import com.your.company.repository.mongo.BaseMongoRepository;
import com.your.company.repository.postgres.BaseJpaRepository;
import com.your.company.repository.redis.BaseRedisRepository;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
#Configuration
#EnableConfigurationProperties(ApplicationProperties.class)
#EnableJpaRepositories(basePackageClasses = {BaseEntity.class, BaseJpaRepository.class})
#EnableMongoRepositories(basePackageClasses = {BaseDocument.class,
BaseMongoRepository.class}, repositoryFactoryBeanClass = EnhancedMongoRepositoryFactoryBean.class)
#EnableRedisRepositories(basePackageClasses = {BaseHash.class, BaseRedisRepository.class})
public class BasicConfiguration {
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
The above is only an example, usually I would split them further into one class each within the same package with names that describes what they are actually configuring, for example: MongoConfiguration.java, JpaConfiguration.java, etc. Note if you decide to go with that design, you need the #Configuration annotation in each of the separate classes
I believe the main issue here is that both of your interfaces PersistencyRepository and CacheRepository are in the same package, and your configurations are both scanning the same package for Spring Data Repository interfaces, creating duplicate bean names. You should separate these repositories into their own packages.
It's important to note that basePackageClasses scans the whole package for applicable interfaces. See the docs for EnableMongoRepositories.basePackageClasses (source):
Type-safe alternative to basePackages() for specifying the packages to scan for annotated components. The package of each class specified will be scanned. Consider creating a special no-op marker class or interface in each package that serves no purpose other than being referenced by this attribute.
Related
I am encountering a baffling #Autowired issue, which only occurred after I added a dependency to one of my own projects.
Here is the situation:
I am extending a service, which has autowired repositories. Here's the simplified version:
package com.opt.custom.domain;
import com.opt.repo.RepositoryOne;
import com.opt.repo.RepositoryTwo;
#Primary
#Service("CustomDomainServiceImpl")
public class CustomDomainServiceImpl extends DomainServiceImpl {
private RepositoryOne repo1;
private RepositorTwo repo2;
#Autowired
public CustomDomainServiceImpl(RepositoryOne repo1
, RepositorTwo repo2) {
super(repo1, repo2);
}
....
}
This has been working fine - the #Autowired tags grab the repositories fine, whether or not I include them as attributes, as I don't use them except to feed into the parent service.
However, I have created another service (with its own service, repositories, etc.). When I add this new service as a dependency of the above project (in the POM file), the #Autowired annotations in the above code stop working, even if I don't reference any of the services, repos, etc. in this class. Specifically, the error is:
Parameter 0 of constructor in com.opt.custom.domain.CustomDomainServiceImpl required a bean of type 'com.opt.repo.RepositoryOne' that could not be found.
Action:
Consider defining a bean of type 'com.opt.repo.RepositoryOne' in your configuration.
I don't know how simply adding a dependency (while not using anything from it) can cause this issue.
I have tried adding a #ComponentScan to the above class:
#ComponentScan(basePackages = {"com.opt.repo"})
But this has not helped.
If it helps, this is the top-level class in the Maven project that I am adding as a dependency:
package com.opt.new.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
#SpringBootApplication
#EntityScan(basePackages = { "com.someotherpackage.persistence.*" })
public class PersistenceClasses {
public static void main(String[] args) {
SpringApplication.run(PersistenceClasses .class, args);
}
}
Thank you for any insights you can provide.
#ComponentScan annotation should be added to the spring boot application class. In your case, its PersistenceClasses. Also, make sure to have a #Repository annotation on your RepositoryOne class
#Repository is a spring stereotype, identifying spring components in an application. More information on it can be found here
I am configuring a spring boot application. So I created a property bean class like this:
import javax.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
#Configuration
#EnableConfigurationProperties
#PropertySource("classpath:/application.properties")
public class APPStaticProperties {
#NotNull
#Value("${dblog.system.name}")
String db_logsystem_name;
/**
* #return the db_logsystem_name
*/
public String getDb_logsystem_name() {
return db_logsystem_name;
}
/**
* #param db_logsystem_name the db_logsystem_name to set
*/
public void setDb_logsystem_name(String db_logsystem_name) {
this.db_logsystem_name = db_logsystem_name;
}
}
And I am creating a object by in the controller class:
#Autowired
APPStaticProperties appStaticProperties;
But I wanted to know how do I pass the this object for use in other projects? Because my code flow goes from the controller to a JSP and then to a class in another project. I need the object available for use in that class. Well to be honest, in many other projects as well! I am not able to figure it out how to do it. Neither are there too many examples out there for reference.
You wouldn't normally inject an #Configuration bean into other Spring managed beans, because it sets up configuration to be used by other Spring managed beans.
For example, because you have declared an #PropertySource, to access your properties in other Spring managed means you can just inject properties into your code elsewhere using #Value. You don't need to inject your APPStaticProperties bean to do this.
I'm learning Spring as it seems to be a very powerful framework. I've already did many getting started guides and now I'm trying with this tutorial. In it, all classes are put in the same package, but to make it more interesting I tried using different packages according to the class (entity, controller, etc.). I was about to test it before the Testing a REST Service section but got an error building the application. This is how my project is structured:
The only difference with the classes in the tutorial is the marked ServletInitializer which comes with the initializr utility (actually I used the one that comes with STS, but it's the same). As far as I understand, it has nothing to do with the problem so the content of this class is irrelevant.
Another minor difference with the tutorial is that the Application class here is called RestServicesApplication but the content is the same.
When I try to build the application (using Gradle's bootRun instead of Maven) I got the following error message:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method init in com.example.restservices.RestServicesApplication required a bean of type 'com.example.repository.AccountRepository' that could not be found.
Action:
Consider defining a bean of type 'com.example.repository.AccountRepository' in your configuration.
:bootRun FAILED
So I tried to annotate AccountRepository with #Bean but it gives me a compilation error saying that the annotation is disallowed for that location. Next I tried with the #Component annotation (also on BookmarkRepository) and adding #ComponentScan("com.example") in RestServicesApplication. After that the error remains but the message changed to
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.example.controller.BookmarkRestController required a bean of type 'com.example.repository.BookmarkRepository' that could not be found.
Action:
Consider defining a bean of type 'com.example.repository.BookmarkRepository' in your configuration.
:bootRun FAILED
I added #Component annotation to BookmarkRestController but the same error message remains. What am I missing here?
Thanks in advance for your answers.
Edit #1
The classes involved in the problem are the following (copied from my project, not the ones in the tutorial, although the differences are minimal):
RestServicesApplication
package com.example.restservices;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import com.example.entity.Account;
import com.example.entity.Bookmark;
import com.example.repository.AccountRepository;
import com.example.repository.BookmarkRepository;
#SpringBootApplication
#ComponentScan("com.example")
public class RestServicesApplication {
public static void main(final String[] args) {
SpringApplication.run(RestServicesApplication.class, args);
}
#Bean
CommandLineRunner init(final AccountRepository accountRepository,
final BookmarkRepository bookmarkRepository) {
return (evt) -> Arrays.asList(
"jhoeller,dsyer,pwebb,ogierke,rwinch,mfisher,mpollack,jlong".split(","))
.forEach(
a -> {
final Account account = accountRepository.save(new Account(a,
"password"));
bookmarkRepository.save(new Bookmark(account,
"http://bookmark.com/1/" + a, "A description"));
bookmarkRepository.save(new Bookmark(account,
"http://bookmark.com/2/" + a, "A description"));
});
}
}
BookmarkRestController
package com.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.repository.AccountRepository;
import com.example.repository.BookmarkRepository;
#RestController
#RequestMapping("/{userId}/bookmarks")
public class BookmarkRestController {
private final BookmarkRepository bookmarkRepository;
private final AccountRepository accountRepository;
#Autowired
public BookmarkRestController(final BookmarkRepository bookmarkRepository,
final AccountRepository accountRepository) {
this.bookmarkRepository = bookmarkRepository;
this.accountRepository = accountRepository;
}
// #RequestMapping methods...
}
AccountRepository
package com.example.repository;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import com.example.entity.Account;
#Component
public interface AccountRepository extends JpaRepository<Account, Long> {
Optional<Account> findByUsername(String username);
}
BookmarkRepository
package com.example.repository;
import java.util.Collection;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import com.example.entity.Bookmark;
#Component
public interface BookmarkRepository extends JpaRepository<Bookmark, Long> {
Collection<Bookmark> findByAccountUsername(String username);
}
Note: I added the imports so you can see where the classes and annotations come from
Edit #2
I tried another thing: I refactored my Project to fit the tutorial and I put everithing in the same package (com.example.bookmarks) and removed the extra annotations. The Project compiles but when I run the Project I get a 404 HTTP status when trying to accesss a REST service. I'm still interested in make it run with my original structure but I want to let you know that this refactoring makes the Project work.
To have Spring create a bean that implements JpaRepository interface, you need to use Spring JPA namespace and activate the repository support using the appropriate element. In xml:
<jpa:repositories base-package="com.example.repository" />
In annotation:
#EnableJpaRepositories
See this docs
This scans all packages below com.example.repository for interfaces extending JpaRepository and creates a Spring bean for it that is backed by an implementation of SimpleJpaRepository.
I think you have to create package again. You packing looking not right. Recreate your package
I was reading this article Exception Handling in Spring MVC, and I don't understand why class extending ExceptionHandlerExceptionResolver doesn't have any annotations to it.
It should be a bean, right? So it must be annotated with #Component (or maybe #Service, but I'm not sure if it belongs to a service layer) annotation or something?
So why it does not have any annotations and how then Spring knows that it's a bean and that it should be used?
You have to manually add your handler to the list of handlers (in the example below I use a SImpleMappingExceptionsResolver, but you can use your own implementation):
package eu.anastasis.readingtrainer.configuration;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
#Configuration
#EnableWebMvc
public class ConfigurationAdapter extends WebMvcConfigurerAdapter {
#Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
exceptionResolvers.add(new SimpleMappingExceptionResolver());
}
}
Please note that in this way you override any #ControllerAdvice + #ExceptionHandler you may have set (I don't know how to combine both strategies).
Just as an update to #Andrea Pegoretti answer,
in Spring 5.X.X WebMvcConfigurerAdapter is deprecated, instead use WebMvcConfigurer interface; please refer to this link for more details.
I'm new to Java and Spring, coming from C# and the .NET world, so bear with me - what I am attempting to do may be off the mark...
I am attempting to configure Spring DI using Java configuration and annotations, not XML configuration, however I am having a few issues. This is for a standalone application, not a web app. I have worked through the springsource documentationand as far as I can tell my very basic configuration should be correct...but isn't. Please take a look at the code below:
Java Configuration Annotated Class:
package birdalerter.common;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import birdalerter.process.ISightingsProcessor;
import birdalerter.process.SightingsProcessor;
#Configuration
#ComponentScan({"birdalerter.process", "birdalerter.common"})
public class AppConfig {
#Bean
#Scope("prototype")
public ISightingsProcessor sightingsProcessor(){
return new SightingsProcessor();
}
}
Configure Component implementing the ISightingsProcessor interface:
package birdalerter.process;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import org.springframework.stereotype.Component;
import birdalerter.domainobjects.IBirdSighting;
#Component
public class SightingsProcessor implements ISightingsProcessor{
private LinkedBlockingQueue<IBirdSighting> queue;
private List<ISightingVisitor> sightingVisitors = new ArrayList<ISightingVisitor>();
public SightingsProcessor(){
}
...
}
Configure Factory Component:
package birdalerter.process;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component
public class ProcessorFactory {
private ISightingsProcessor sightingsProcessor;
#Autowired
#Required
private void setSightingsProcessor(ISightingsProcessor sightingsProcessor){
this.sightingsProcessor = sightingsProcessor;
}
public ISightingsProcessor getSightingsProcessor(){
return this.sightingsProcessor;
}
}
Wire up the AnnotationConfigApplicationContext and test:
#Test
public void testProcessingDI(){
#SuppressWarnings("resource")
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(AppConfig.class);
context.refresh();
ISightingsProcessor processor = new ProcessorFactory().getSightingsProcessor();
System.out.println(processor);
Assert.assertTrue(processor != null);
}
The SightingsProcessor is not being setter injected and the assert is failing as the returned object is null. Hopefully I have missed something very obvious.
Thanks in advance.
Edited in Response to Meriton:
Thanks for the answer Meriton.
Why would Spring not know about the newly created object? Does Spring not maintain dependencies throughout the application lifecycle and inject as appropriate when new objects are created that are configured as beans?
I don't want to directly use context.getBean(ISightingsProcessor.class) if I can help it to be honest, I would like the dependency injected in the setter method without having manual intervention - it just seems cleaner.
I am using the ProcessorFactory as the ISightingsProcessor interface extends Runnable - the implementing object is to be started as a thread. The application will be configurable to have n* threads, with each being started within a loop iteration. I don't think it is possible (I may be wrong, please advise if so) to have #Autowired annotations within method declarations, hence I use the factory to supply a new instance of the injected ISightingsProcessor concrete class.
Yes I've just had a look regarding the #Scope annotation - you are right, that needs moving to the AppConfig #Bean declaration (which I've done in this edit), thanks for that.
ISightingsProcessor processor = new ProcessorFactory().getSightingsProcessor();
This calls the constructor of ProcessorFactory, and then the getter of the instance the constructor created. Spring can not know about that newly created object, and therefore not inject its dependencies. You should ask Spring for the ProcessorFactory instead, for instance with
ProcessorFactory pf = context.getBean(ProcessorFactory.class);
ISightingsProcessor processor = pf.getSightingsProcessor();
That said, I don't know why you need class ProcessorFactory at all. You might just as well get the ISightingsProcessor directly:
ISightingsProcessor processor = context.getBean(ISightingsProcessor.class);
Additionally, "Java Based Configuration" and component scanning are independent ways to declare beans. Currently, you are therefore declaring the ISightingsProcessor twice: Once with the #Bean-annotated factory method, and once with the component scan and the #Component annotation on the class. Doing either of that will do. In fact, doing both might cause one bean definition to override the other.
Oh, and the #Scope annotation is for bean definitions (those you annotate with #Bean or #Component). It will likely be ignored on injection points (#Autowired).