How to create repository for more than one entity? - spring

I'm trying to create a simple web-site, which hosts topics and comments. I've begun with topics, and created repository for them:
package com.myProject.mvc3.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface TopicRepository extends CrudRepository<Topic, Integer>{
public List<Topic> findAllByTopicTag(Tag currentTag);
}
And I've defined the path for my repository in the servlet-context.xml:
jpa:repositories base-package="com.myProject.mvc3.repository"
Now, I'd like to include the comments in my repository, and the following code doesn't work:
package com.myProject.mvc3.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CommentRepository extends CrudRepository<Comment, Integer> {
public List<Comment> findTopicComments(Topic topic);
}
My project doesn't build even. Can you give me an advice, how to create repositories for more than one entities (Topic class and Comment class are declared with #Entity)?
What i'm faciong:
there is HDD pic on the TopicRepository class icon
there is a question mark on the CommentRepository class icon
error log (a huge one):
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'topicController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.epam.mvc3.service.CommentService com.epam.mvc3.controller.TopicController.commentService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'commentService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.epam.mvc3.repository.CommentRepository com.epam.mvc3.service.CommentService.commentRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'commentRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: No property find found for type class com.epam.mvc3.model.Comment
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:467)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:483)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:358)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:325)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
com.springsource.insight.collection.tcserver.request.HttpRequestOperationCollectionValve.invoke(HttpRequestOperationCollectionValve.java:84)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:539)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:298)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
java.lang.Thread.run(Thread.java:722)

Just add By in findTopicComments so that it became findByTopicComments. Of course, this will work only if Comment entity has topicComments field or it has topic field which, in turn, has comments field.
Btw, you don't need #Repository annotation on Spring-data-jpa repositories.
Actually, if your query name doesn't match pattern ^(find|read|get)(\\p{Upper}.*?)??By from this class then the following occurs:
any of the prefixes such as get, 'read' and find won't be stripped and will be considered as the part of a JPQL query to generate. In this case you will get an exception:
java.lang.IllegalArgumentException: No property find found for type class ....
if there's nothing to strip from your method name then it will be processed as if it had findBy prefix before.
Since this is not clear from docs I've created the issue in Spring Data Commons issue tracker.

Try to write your repositories in such way:
#Repository
public interface TopicRepository extends JpaRepository<Topic, Integer> >{
#Query("select topic from Topic topic where topic.topicTag.id=?1")
public List<Topic> findAllByTopicTag(int topicTagId);
}
#Repository
public interface CommentRepository extends JpaRepository<Comment, Integer> {
#Query("select comment from Comment comment where comment.topic.id=?1")
public List<Comment> findTopicComments(int topicId);
}
In this example I specify id of the entities as search criteria because usually they are used as foreign key. You can easily add additional search criteria if you need.
More details about query methods in Spring Data you can find in reference documentation.
Update
About your error stack trace - I think this error means that you don't specify your classes in persistent.xml.
There is also a way to not specify all classes in your persistent.xml -> look here and here for details.
Also with Spring you can easily configure your JPA project without persistent.xml file if you use full java config. For example:
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean factoryBean =
new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan(new String[] {"com.dimasco.springjpa.domain"});
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
//vendorAdapter.setGenerateDdl(generateDdl)
factoryBean.setJpaVendorAdapter(vendorAdapter);
Properties additionalProperties = new Properties();
additionalProperties.put("hibernate.hbm2ddl.auto", "update");
factoryBean.setJpaProperties(additionalProperties);
return factoryBean;
}
As you can see in this example I simply define what packages to scan.

Related

EnversRevisionRepositoryFactoryBean dosenot create bean for JPARepositories

I am using spring boot, hibernate enverse. I have following dependency in pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-envers</artifactId>
</dependency>
following is my envers config.
#Configuration
#EnableJpaRepositories(repositoryFactoryBeanClass =
EnversRevisionRepositoryFactoryBean.class, basePackages = {
"com.example.persistence" })
public class EnversConf
{
}
So package com.example.persistence have PersonDAO and AddressDAO and also Entities.
I have following two DAOs,
interface PersonDAO extends RevisionRepository<PersonEntity, Integer, Integer>, JpaRepository<PersonEntity, Integer>{}
interface AddressDAO extends JpaRepository<AddressEntity, Integer>{}
I have two entities PersonEntity which I want to audit and AddressEntity which I don't want to audit.
Now I have following two services,
class PersonServiceImpl implements PersonService{
#Autowire PersonDAO personDAO;
}
class AddressServiceImpl implements AddressService{
#Autowire AddressDAO addressDAO;
}
When I add #EnableJpaRepositories(...) config it unable to get beans for AddressDAO. I thought EnversRevisionRepositoryFactoryBean works for both RevisionRepository and JpaRepository.
I got following exception stacktrace,
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'addressService': Unsatisfied dependency expressed through field 'addressDAO'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addressDAO': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findAll found for type AddressEntity!
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'addressDAO': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property findAll found for type AddressEntity!
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property findAll found for type AdressEntity!
Am I missing any configuration.
Got solution ;)
Need to create two separate configuration classes as we cannot use TWO #EnableJpaRepositories on same configuration class.
So have created following two configuration classes,
#EnableJpaRepositories(basePackages = "com.example.jpa.dao")
class JpaConfig {}
#EnableJpaRepositories(repositoryFactoryBeanClass = EnversRevisionRepositoryFactoryBean, basePackages = "com.example.envers.dao")
class EnversConfig {}

BeanCurrentlyInCreationException when spring starts

I am getting the BeanCurrentlyInCreationException when I start my spring application.
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.datayes.bdb.rrp.business.service.impl.StockModelBaseService com.datayes.bdb.rrp.business.service.impl.StockModelV3ServiceImpl.stockModelBaseService; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'stockModelBaseService': Bean with name 'stockModelBaseService' has been injected into other beans [researchFrameworkCommonServiceImpl] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 71 more
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'stockModelBaseService': Bean with name 'stockModelBaseService' has been injected into other beans [researchFrameworkCommonServiceImpl] in its raw version as part of a circular reference, but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching - consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:568)
And here are the code snippets I have found caused this issue:
#Component public class KafkaConsumerServer implements MessageListener<String, String> {
#Autowired StockModelV3Service stockModelV3Service;
#Autowired FinanceIndicatorService financeIndicatorService;
......
}
#Service public class FinanceIndicatorServiceImpl implements FinanceIndicatorService {
#Autowired StockModelV3Service stockModelV3Service;
#Autowired IndustryResearchFrameworkService industryResearchFrameworkService;
......
}
#Service public class IndustryResearchFrameworkServiceImpl implements IndustryResearchFrameworkService {
#Autowired ResearchFrameworkCommonService commonService;
......
}
#Service public class ResearchFrameworkCommonServiceImpl implements ResearchFrameworkCommonService {
#Autowired StockModelBaseService stockModelBaseService;
......
}
I found some thing interesting in the following article may have explained why.
https://blog.imaginea.com/spring-bean-creation-is-not-thread-safe/
As both my StockModelV3Service and FinanceIndicatorService depends on stockModelBaseService(FinanceIndicatorService -> industryResearchFrameworkService -> researchFrameworkCommonService -> stockModelBaseService), during spring bean creation, they have raced against each other. Which caused BeanCurrentlyInCreationException. As the above article noted, spring bean creation is not thread safe.
To solve this problem seems easy. I changed autowire order as below:
public class KafkaConsumerServer implements MessageListener<String, String> {
#Autowired FinanceIndicatorService financeIndicatorService;
#Autowired StockModelV3Service stockModelV3Service;
As FinanceIndicatorService also depends on StockModelV3Service, so when financeIndicatorService is loaded, it will wait till stockModelV3Service is loaded then load itself. Thus avoid BeanCurrentlyInCreationException.
After all, it has nothing to do with circular reference. As StockModelBaseService doesn't depends on other services.

MongoDB configuration in Spring Boot and Spring Data REST

I want to use MongoDB for the mongoDB with spring-boot and JPA.. I'm able to do with embedded H2 database. But I'm not sure what's going wrong using mongo-db. While running the application, I'm getting error that datasource is missing.
#EnableAutoConfiguration
#EnableJpaRepositories(basePackages = "com..........repo")
#EnableWebMvc
#Configuration
#ComponentScan
#Import({ SpringMongoConfig.class, RepositoryRestMvcConfiguration.class })
public class Bootstrap extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Bootstrap.class);
}
}
.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
#Configuration
#EnableMongoRepositories(basePackages = "com.............repo")
#PropertySource(value = "classpath:mongo-config.properties")
public class SpringMongoConfig extends AbstractMongoConfiguration {
#Value("${MONGO_DB_HOST}")
private String MONGO_DB_HOST;
#Value("${MONGO_DB_PORT}")
private int MONGO_DB_PORT;
#Value("${DB}")
private String DB;
#Override
protected String getDatabaseName() {
return DB;
}
#Bean
#Override
public Mongo mongo() throws Exception {
return new MongoClient(MONGO_DB_HOST, MONGO_DB_PORT);
}
}
.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:293)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
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)
..........................
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:509)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:290)
... 25 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
....................................
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 39 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath.
at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.getDriverClassName(DataSourceProperties.java:93)
at org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource(DataSourceAutoConfiguration.java:105)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
For starters use the framework Spring Boot will do autoconfiguration for the frameworks it detects. This includes Spring Data JPA and Spring Data Mongo. So you can remove the #Enable annotation for it.
The same for Spring MVC and Spring Data Rest.
To allow Spring Boot to configure Spring Mongo add the following properties to your application.properties
spring.data.mongodb.host= # the db host
spring.data.mongodb.port=27017 # the connection port (defaults to 27107)
or the
spring.data.mongodb.uri=mongodb://localhost/test # connection URL
More on the Spring Boot Mongo support can be found in this section of the Spring Boot Reference Guide.
When not using an embedded datasource you have to specify which driver to use for this add the following property to your application.properties. This is also documented in this section of the Spring Boot Reference Guide.
spring.datasource.driverClassName=your.driver.class
I suggest moving your Bootstrap class to a top level package and remove all not needed annotations and configuration files
#EnableAutoConfiguration
#Configuration
#ComponentScan
public class Bootstrap extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Bootstrap.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Bootstrap.class);
}
}
Should be enough to bootstrap your whole application including jpa, mongo and web support.
For a quite complete list I suggest Appendix A of the Spring Boot Reference Guide.

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