spring data JPA common #EnableJpaRepositories for multiple projects - shared jar - spring

i'm using spring boot 2.2.5.RELEASE and spring-data-2.2.5.RELEASE
we have multiple projects in different git repositories and I'm trying to create a common JSON repository to work with MySQL JSON functions via shared jar.
i created the following in my common jar which has an autoconfiguration
#NoRepositoryBean
public interface JsonRepository <T>{
int appendToArray(T entity, String arrayPath, Object item, String storeId) throws JsonProcessingException;
int removeFromArrayByValue(T entity, String arrayPath, String feild, String value, String storeId);
}
configuration class
#EnableJpaRepositories(repositoryBaseClass = JsonRepositoryImpl.class,
repositoryFactoryBeanClass = JsonRepositoryFactoryBean.class
)
#Configuration
public class RepositoryConfig {
}
and i have a spring.factorie files in my resources which configures this as autoconfiguration
and my implementation repository
#Repository
public interface SettingsRepository extends JsonRepository<Settings>, CrudRepository<Settings, Long> {
}
the problem
when i consume my common jar which include all json commons i made, spring-data stopes detecting all repositories and i can't start the application because of missing beans
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'XXXService' defined in file [XXXService.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xxx.XXXRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:228)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789)
it only works if i add another #configuration in the consuming project, and i want to make it work automatically to save defining it on every project i want to add JSON query capabilities
#EnableJpaRepositories(
repositoryBaseClass = JsonRepositoryImpl.class,
repositoryFactoryBeanClass = JsonRepositoryFactoryBean.class,
basePackages = "xxx.*"
)
public class CoreConfig {
}
how i can fix it ??

Related

repository binding problem with spring r2dbc

I try to use Spring R2DBC with postgres driver. I have the following repository:
package fr.misc.database.repos.computed;
import fr.misc.database.entities.computed.OrdreDeTravailPivotComputedEntity;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
public interface OrderRepository extends ReactiveCrudRepository<OrderEntity, String> {
}
And I tried several annotations like that:
package fr.misc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
#EnableJpaRepositories(basePackages = {"fr.misc.database.repos.common"})
#EntityScan("fr.misc")
#ComponentScan("fr.misc")
#SpringBootApplication
#EnableConfigurationProperties
#EnableR2dbcRepositories("fr.misc.database.repos.computed")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
With my connection factory like this:
package fr.misc;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration;
#Configuration
public class DatabaseConfiguration extends AbstractR2dbcConfiguration {
#Value("${spring.data.postgres.host")
private String host;
#Value("${spring.data.postgres.port}")
private int port;
#Value("${spring.data.postgres.database}")
private String database;
#Value("${spring.data.postgres.username}")
private String username;
#Value("${spring.data.postgres.password}")
private String password;
#Override
public ConnectionFactory connectionFactory() {
// return new PostgresqlConnectionFactory(PostgresqlConnectionConfiguration.builder().host(host)
// .port(port).database(database).username(username).password(password).build());
return ConnectionFactories.get(ConnectionFactoryOptions.builder()
.option(DRIVER, POSTGRESQL_DRIVER)
.option(DATABASE, database)
.option(HOST, host)
.option(PORT, port)
.option(PASSWORD, password)
.option(USER, username)
.build());
}
}
and the application.yml:
data:
postgres:
host: locahost
port: 5432
database: postgres
username: postgres
password: postgres
But I always got the following exception:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderConverter' defined in file [../converters/OrderConverter.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'fr.misc.database.repos.computed.OrderRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:228)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:126)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
... 63 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'ffr.misc.database.repos.computed.OrderRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1695)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1253)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:885)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:789)
... 81 more
And bellow my OrderConverter constructor:
#Slf4j
#Component
public class OrderConverter {
private final OrderComputedRepository orderComputedRepository;
#Autowired
public OrderConverter(OrderComputedRepository orderComputedRepository) {
this.orderComputedRepository = orderComputedRepository;
}
Do you have an idea why my repository bean isn't bound ?
Thank all and best regards
Adrian
The error says:
No qualifying bean of type 'ffr.misc.database.repos.computed.OrderRepository'
Looks like there is an additional 'f' at the beginning of your package.
So I don't know if the code you shared is the exact one, but at least it does not match your annotation
#EnableR2dbcRepositories("fr.misc.database.repos.computed")

Spring JPA not implementing/autowiring repository despite #EnableJpaRepositories annotation

I'm getting an exception when I start my application, where Spring complain about UnsatisfiedDependencyException:
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'applicationConfig': Unsatisfied dependency expressed through field 'controlRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.oak.api.finance.repository.ControlRepository]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
My application is organized in this format:
I declared my repository interfaces, with the proper Spring JPA annotations:
#RepositoryRestResource(collectionResourceRel = "exchange", path = "exchanges")
public interface ControlRepository extends PagingAndSortingRepository<Control, Long> {
}
I annotated the EntryPoint class that contains the main method
#SpringBootApplication
#EntityScan(basePackages = {"com.oak.api.finance.model.dto"})
#EnableJpaRepositories(basePackages = {"com.oak.api.finance.repository"})
public class EntryPoint {
public static void main(String[] args) {
Logger logger = LogManager.getLogger(EntryPoint.class);
logger.info("Starting application");
ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
// SpringApplication.run(EntryPoint.class, args);
ctx.getBean(ApplicationServer.class).start();
}
I used #Autowired to inject my repository into my spring config (java based) ApplicationConfig class:
#Autowired
private ControlRepository controlRepository;
#Autowired
private CompanyRepository companyRepository;
#Autowired
private SectorRepository sectorRepository;
Essentially I want to control the dependency on Spring and limit it to a couple of packages, (the repositories, the java config, and the program entry point - EntryPoint)
I assumed that, by specifying #EnableJpaRepositories with the package where my repositories are located, spring would create a proxy for my repository and instantiate an instance of that, and that by the time I call :
ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class)
The repositories instances would be present in the beans poole and would be possible to autowire them into my ApplicationConfig context, and then inject them into my controller.
This is clearly not happening, and Spring is complaining about the missing Bean to autowire, but I'm not sure what am I missing.
Below a snapshot of my packages:
any ideas?
My guess is your repositories are not being scanned, so as a result beans are not getting created. Can you try removing these 2 annotations
#EntityScan(basePackages = {"com.oak.api.finance.model.dto"})
#EnableJpaRepositories(basePackages = {"com.oak.api.finance.repository"})
And keep only #SpringBootApplication. If this is not working, you might need to check the package structure (if possible paste a screenshot here)
Edit 1
replace #SpringBootApplication with
#Configuration
#EnableAutoConfiguration
#ComponentScan("com.oak")
Edit2
Use
new SpringApplicationBuilder()
.sources(SpringBootApp.class)
.web(false)
.run(args);
Or use CommandLineRunner after changing ComponentScan path to "com.oak" as mh-dev suggested

error springboot #autowired dependency

I try do a fill repository with metrics in spring boot, but I have the problem that when I execute I recive error.
This is my error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'actuatorMetricsPrinter' defined in file [ActuatorMetricsPrinter.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.util.Collection]: : No qualifying bean of type [org.springframework.boot.actuate.endpoint.PublicMetrics] found for dependency [collection of org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.endpoint.PublicMetrics] found for dependency [collection of org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:747)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1115)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at hello.Application.main(Application.java:14)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.boot.actuate.endpoint.PublicMetrics] found for dependency [collection of org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1118)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:919)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:862)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:811)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:739)
... 18 common frames omitted
And this is my code when I recive error:
#Autowired
public DummyController(ActuatorMetricsPrinter metricsPrinter) {
this.metricsPrinter = metricsPrinter;
}
I have a class ActuatorMetricsPrinter that show the metrics but I have a problem when try fill this repository
*EDIT *
#Component
public class ActuatorMetricsPrinter {
private MetricRepository repository;
private static final String TEMPLATE = "Metric: %s [%s]";
private Collection<PublicMetrics> publicMetrics = null;
public String printAllMetrics() {
StringBuilder sb = new StringBuilder();
for (PublicMetrics pm : publicMetrics) {
sb.append("Public Metric: " + pm.getClass().getName());
sb.append("\n\n");
for (Metric<?> m : pm.metrics()) {
sb.append(String.format(TEMPLATE, m.getName(), m.getValue().toString()));
sb.append("\n");
}
}
return sb.toString();
}
#Autowired
public void MetricExporterService(MetricRepository repository) {
this.repository = repository;
}
And
#Controller
public class DummyController {
private final ActuatorMetricsPrinter metricsPrinter;
#Autowired
public DummyController(ActuatorMetricsPrinter metricsPrinter) {
this.metricsPrinter = metricsPrinter;
}
#RequestMapping(value = "/customMetrics", method = RequestMethod.GET)
#ResponseBody
public String printMetrics() {
return metricsPrinter.printAllMetrics();
}
#Bean
public ActuatorMetricsPrinter publicMetrics() {
return new ActuatorMetricsPrinter();
}
}
Thank you very much!
Spring beans factory not found a bean Collection<PublicMetrics> publicMetrics for autowarid; try to create a list of PublicMetrics
see : Spring autowire a list
Auto-wiring a List using util schema gives NoSuchBeanDefinitionException
In your case the actual problem is initializing the constructor for ActuatorMetricsPrinter. You have it Autowired to take in a Collection so Spring is trying to find the set of PublicMetrics beans to use as a collection and it cannot find any. Here is the error in what you provided above that points to that. I ran into the same issue myself at one point.
No qualifying bean of type
[org.springframework.boot.actuate.endpoint.PublicMetrics] found for
dependency [collection of
org.springframework.boot.actuate.endpoint.PublicMetrics]: expected at
least 1 bean which qualifies as autowire candidate for this
dependency.
From the Spring Docs on Autowired:
In case of a Collection or Map dependency type, the container will
autowire all beans matching the declared value type. In case of a Map,
the keys must be declared as type String and will be resolved to the
corresponding bean names.
Since the PublicMetrics are not declared as beans I think the right way to do it is by autowiring to a MetricRepository. See this link and the Exporting Metrics section there as a reference. There is a link to a sample application. Here is some modified code that you can use.
#Autowired
public MetricExporterService(MetricRepository repository) {
this.repository = repository;
}
public String printAllMetrics() {
StringBuilder sb = new StringBuilder();
for (Metric metric : repository.findAll()) {
sb.append(String.format(TEMPLATE, metric.getName(), metric.getValue().toString()));
}
return sb.toString();
}

Spring and Spring Data JPA are not working in conjunction

I am using Spring Data JPA (1.3.0.RELEASE) with Spring (3.2.2.RELEASE ) in one project and facing a weird problem. I am using xml based configuration as mentioned below.
<context:annotation-config/>
<context:component-scan base-package="x.y.z.services"/>
Using this configuration to scan the classes decorated with #Component, #Service and #Named annotations.
<jpa:repositories base-package="x.y.z.repo"/>
Using this configuration to scan all interfaces extending JpaRepository. These interfaces are injected in Service classes in the following way.
#Service
public class UserServiceImpl implements UserService {
private UserRepository userRepository;
#Inject
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
#Override
public List<User> listUsers() {
return userRepository.findAll();
}
}
This configuration works as expected without any issue. But when I add the following configuration I get the BeanCreationException for UserRepository.
<bean id="securityRealm" class="x.y.z.Realm">
<property name="userService">
<bean class="x.y.z.services.UserServiceImpl"/>
</property>
</bean>
And, here is the Java code for Realm and UserRepository.
public class Realm extends AuthorizingRealm implements IRealm {
private UserService userService;
#Inject
public void setUserService(UserService userService) {
this.userService = userService;
}
#Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
return null;
}
}
public interface UserRepository extends JpaRepository<User, String> {
}
As per above configuration, Spring is able to create the bean for userService but not able to create the UserRepository bean.
I can get this error away by scanning x.y.z.Realm and decorating it with #Service annotation. But it will be a very big constraint and design issue to my application.
AFAICT, Spring is not able to create the bean for UserRepository as it's implementation class is not available and has to be provided by jpa:repositories configuration. I can see that Spring and Spring Data JPA are not working in conjunction.
Can somebody please help me to solve this problem. Below is stacktrace of the exeception.
2013-04-30 21:44:04.745:INFO:/web:Initializing Spring root WebApplicationContext
2013-04-30 21:44:07,009 [ERROR] [main] [org.springframework.web.context.ContextLoader] - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shiroFilter' defined in class path resource [META-INF/Test-web/security-config.xml]: Cannot resolve reference to bean 'securityManager' while setting bean property 'securityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testShiroRealm': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: x.y.z.core.service.UserService x.y.z.core.security.testShiroRealm.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void x.y.z.core.service.internal.UserServiceImpl.setUserRepository(x.y.z.repo.UserRepository); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [x.y.z.repo.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1134)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
at org.springframework.context.support.AbstractApplicationContext.registerBeantesttProcessors(AbstractApplicationContext.java:753)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:389)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:294)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112)
at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:764)
at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:406)
at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:756)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:242)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1221)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:699)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:454)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:90)
at org.eclipse.jetty.server.Server.doStart(Server.java:263)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:59)
at runjettyrun.Bootstrap.main(Bootstrap.java:80)
... 34 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void x.y.z.core.service.UserServiceImpl.setUserRepository(x.y.z.repo.UserRepository); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [x.y.z.repo.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:601)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
... 45 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [x.y.z.repo.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.java:558)
... 47 more
This was the bug in Spring Data JPA and has been fixed. Please have a look at JIRA issue for resolution.
https://jira.springsource.org/browse/DATAJPA-335

Spring error when trying to manage several classes that share a common base class?

Im currently using Spring 3.0.x ..
Im wondering what's wrong with these structures,
where i would like to manage the subclasses but not the parent classes.
I have 2 child DAOs extending the BaseDAO :
public abstract class BaseDAO<K, E> {
....
}
#Repository
public class UserDAO extends BaseDAO<String, User> {
....
}
#Repository
public class ApprovalDAO extends BaseDAO<String, Approval> {
....
}
And i have the services like this, with hierarchies like this :
public abstract class BaseService<K, E extends BaseEntity, D extends BaseDAO<K, E>> {
#Autowired
protected D dao;
....
}
public abstract class BaseCommonService<K, E extends BaseCommonEntity, D extends BaseDAO<K, E>> extends BaseService<K,E,D> {
....
}
#Service
public class UserService extends BaseCommonService<String, User, UserDAO> {
....
}
When trying to inject the userservice object to my application, it throws error like this :
Exception in thread "main"
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'testEntities': Injection of autowired
dependencies failed; nested exception
is
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private
com.primetech.module.common.service.UserService
com.primetech.module.purchase.app.TestEntities.userService;
nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'userService': Injection of autowired
dependencies failed; nested exception
is
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: protected
com.primetech.core.parent.BaseDAO
com.primetech.core.parent.BaseService.dao;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type
[com.primetech.core.parent.BaseDAO] is
defined: expected single matching bean
but found 2: [userDAO, approvalDAO]
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1064)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:574)
at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at
org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at
org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:93)
at
com.primetech.module.purchase.app.TestEntities.main(TestEntities.java:81)
Caused by:
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private
com.primetech.module.common.service.UserService
com.primetech.module.purchase.app.TestEntities.userService;
nested exception is
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'userService': Injection of autowired
dependencies failed; nested exception
is
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: protected
com.primetech.core.parent.BaseDAO
com.primetech.core.parent.BaseService.dao;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type
[com.primetech.core.parent.BaseDAO] is
defined: expected single matching bean
but found 2: [userDAO, approvalDAO]
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:507)
at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:283)
... 13 more Caused by:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name
'userService': Injection of autowired
dependencies failed; nested exception
is
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: protected
com.primetech.core.parent.BaseDAO
com.primetech.core.parent.BaseService.dao;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type
[com.primetech.core.parent.BaseDAO] is
defined: expected single matching bean
but found 2: [userDAO, approvalDAO]
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:286)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1064)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:838)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:780)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:697)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 15 more Caused by:
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: protected
com.primetech.core.parent.BaseDAO
com.primetech.core.parent.BaseService.dao;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type
[com.primetech.core.parent.BaseDAO] is
defined: expected single matching bean
but found 2: [userDAO, approvalDAO]
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:507)
at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:283)
... 26 more Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type
[com.primetech.core.parent.BaseDAO] is
defined: expected single matching bean
but found 2: [userDAO, approvalDAO]
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:697)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
... 28 more
I tried changing this section, removing the #Repository annotation :
#Repository
public class ApprovalDAO extends BaseDAO<String, Approval> {
....
}
into this :
public class ApprovalDAO extends BaseDAO<String, Approval> {
....
}
And things run without error, but then, the approvalDAO isnt managed by the spring anymore, and cannot be injected later by #Autowired
Any suggestions on how i can solve this problem ?
Autowiring works only if there is exactly one implementation bean of the specific type present in the Spring Context. I'd assume that using the generic D extends BaseDao leads to a situation where Spring is trying to autowire instances of BaseDao instead of UserDao and ApprovalDao. Because you both UserDao and ApprovalDao implement BaseDao, Spring context contains multiple implementations of BaseDao and cannot decide which one should be used.
Spring is trying to tell this to you in the stack trace
org.springframework.beans.factory.NoSuchBeanDefinitionException:
__No unique bean of type__ [com.primetech.core.parent.BaseDAO] is defined:
expected single matching bean but found 2: [userDAO, approvalDAO]
You could try to test this by defining the dao in the concrete service using the actual dao type e.g.
public abstract class BaseService<K, E extends BaseEntity, D extends BaseDAO<K, E>> {
private final D dao;
protected BaseService(D dao) {
this.dao = dao;
}
}
public class UserService extends BaseService<K, User, UserDao<K, User>> {
#Autowired
public UserService(UserDao dao) {
super(dao);
}
}
I'd continue by defining interfaces for UserDao and ApprovalDao so that dependencies are on interfaces and not implementations. The daos may still have a common super interface and their implementations may be based on the BaseDao to avoid unnecessary duplication.
In the example I've defined the injected Dao in the constructor because I assume that the same dao instance should be used throughout the lifetime of the service and the service cannot exist without the dao set. In my opinion, a constructor argument communicates this contract better. Furthermore it might make the class a bit more testable and maintainable.

Resources