I and trying to autowire a service interface in the controller but i am getting an error, please help. Codes below :
Exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoComponentController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.rapidinstinct.avia.plat.service.component.TodoCS com.rapidinstinct.avia.plat.service.rest.controller.TodoComponentController.tocs; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.rapidinstinct.avia.plat.service.component.TodoCS] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Controller class
#RestController
#RequestMapping ("/todo")
public class TodoComponentController extends BaseController {
private static Logger _LOG = LoggerFactory.getLogger(TodoComponentController.class);
#Autowired TodoCS tocs;
#RequestMapping(method = RequestMethod.POST)
public create() {
return null;
}
}
Service Interface
#Service
public interface TodoCS extends ComponentService {
}
XML file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
>
<context:annotation-config />
<context:component-scan base-package="com.rapidinstinct.avia.plat.service, com.rapidinstinct.avia.plat.cbo.mapper, com.rapidinstinct.avia.plat.bo.project.mapper"/>
</beans>
You have to annotate the implementation of TodoCS Not the interface itself.
#Service
public class TodoCSImpl implements TodoCS {
}
Then you can autowire the class.
You need a class which implements TodoCS interface. Then, annotation the implementation class with #Component annotation.
Spring, at time of context initialization is trying to search a bean name TodoCS in package : com.rapidinstinct.avia.plat.service.component.TodoCS.
And in configuartion file you mentioned package name as : com.rapidinstinct.avia.plat.service. Try adding com.rapidinstinct.avia.plat.service.component.TodoCS in base package scan as below:
<context:component-scan base-package="com.rapidinstinct.avia.plat.service, com.rapidinstinct.avia.plat.cbo.mapper, com.rapidinstinct.avia.plat.bo.project.mapper,com.rapidinstinct.avia.plat.service.component"/>
Related
I'm in an older Spring app which doesn't use annotations.
My task is very simple, get a Session Bean from applicationContext.xml (inside a Struts action), but getting this error:
java.lang.IllegalStateException: No Scope registered for scope 'session'
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<!-- Session-scoped bean -->
<bean id="techSuppRoleUserInPROD" class="myapp.util.TechSuppRoleUserInPROD"
scope="session" />
Attempting to get it from this sample Struts Action:
public class LandingAction extends ActionSupport {
public String execute() {
// 1. Obtain ApplicationContext
ClassPathXmlApplicationContext applicationContext =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 2.Obtain managed session bean
TechSuppRoleUserInPROD techSuppRoleUserInPROD = (TechSuppRoleUserInPROD)
applicationContext.getBean("techSuppRoleUserInPROD");
}
}
I have to fix the following error. Anyone can help
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'searchController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire method: public void
com.website.dev.controller.SearchController.setRecordingService(com.website.dev.service.RecordingService);
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.website.dev.service.RecordingService]
found for dependency: expected at least 1 bean which qualifies as
autowire candidate for this dependency. Dependency annotations: {}
#Controller
public class SearchController {
private RecordingService recordingService;
#Autowired
public void setRecordingService(RecordingService recordingService) {
this.recordingService = recordingService;
}
#RequestMapping("/search")
public String showSearch(){
return "search";
}
}
#Service("recordingService")
public interface RecordingService {
//methods
}
public class RecordingServiceImpl implements RecordingService {
#Autowired
private RecordingRepository recordingRepository;
//methods that use recordingRepository
}
public interface RecordingRepository {
}
#Repository
public class RecordingJpaRepository implements RecordingRepository {
#PersistenceContext
private EntityManager entityManager;
//methods that use entityManager
}
service-context.xml
<context:annotation-config></context:annotation-config>
<context:component-scan
base-package="com.website.dev.service">
</context:component-scan>
</beans>
website-servlet.xml
<context:component-scan
base-package="com.website.dev.controller"> // searchcontroller is in this package
</context:component-scan>
web.xml
<context:component-scan
base-package="com.enepath.dev.controller">
</context:component-scan>
EDIT
If I autowire RecordingServiceImpl I get the following
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'recordingServiceImpl': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.website.dev.repository.RecordingRepository
com.website.dev.service.RecordingServiceImpl.recordingRepository;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.website.dev.repository.RecordingRepository] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for
this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
I added the following configuration in service-context.xml and this solved my issue
<context:annotation-config></context:annotation-config>
<context:component-scan
base-package="com.website.dev.service">
</context:component-scan>
<context:component-scan
base-package="com.website.dev.repository">
</context:component-scan>
<context:component-scan
base-package="com.website.dev.repository.jpa">
</context:component-scan>
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.website.dev.service.RecordingService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
If we look above exception, we will find that spring container is unable to create or instantiate the bean of type com.website.dev.service.RecordingService.
It is because POJO class is not managed by spring container.
#Autowire annotation will work only those objects which are managed by spring (ie created by the spring container).
you should annotate the RecordingServiceImpl class as Service
#Service
public class RecordingServiceImpl implements RecordingService
and remove #Service("recordingService") from
public interface RecordingService {
//methods
}
RecordingServiceImpl would be managed by Spring container and spring would be able to create the bean.
I'm having this configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mongo:repositories base-package="com.x.record.persistence.repo"
mongo-template-ref="mongoTemplate" />
<context:component-scan base-package="com.x.record.persistence.impl" />
</beans>
where in the package com.x.record.persistence.impl I have a component that needs the repository from com.x.record.persistence.repo.
This is working for spring-data-mongodb version 1.5.2.RELEASE
If I upgrade to the any version greater than 1.6.0.RELEASE (I tried with 1.6.2 and 1.7.0) this no longer works.
It is as if the mongo repository scan does not work and I get the error:
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'noAuthRecordPersistenceService': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Could not autowire field: private com.x.record.persistence.repo.RecordRepository com.x.record.persistence.impl.NoAuthRecordPersistenceServiceImpl.repo;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [com.x.record.persistence.repo.RecordRepository] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency.
Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Any ideas?
UPDATE:
If I use MongoRepository instead of PagingAndSortingRepository it works:
THIS DOES NOT WORK (with 1.6.x and up):
public interface RecordRepository extends PagingAndSortingRepository, RecordRepositoryCustom {
Page<Record> findByOrgHierarchy( String orgId, Pageable pageable );
Record findOneByIdAndOrgHierarchyIn( String id, Collection<String> orgIds );
int countByGsRunId(String gsRunId);
}
THIS WORKS (with 1.6.x and up):
public interface RecordRepository extends MongoRepository, RecordRepositoryCustom {
Page<Record> findByOrgHierarchy( String orgId, Pageable pageable );
Record findOneByIdAndOrgHierarchyIn( String id, Collection<String> orgIds );
int countByGsRunId(String gsRunId);
}
The wirdest thing is that I have other repos that DO WORK with PagingAndSortingRepository
Try sample here, if this works in latest version then its possible that some component of yours is still using a older version and an incompatible state might exists.
Paste your complete code so that community can test the issue.
Trying to use the Spring Data JPA to generate the DAO objects automatically using the <repositories /> with the base-package linking the package that contains the DAO interfaces like:
public interface UserDAO extends JpaRepository<User, String> {
}
but it fails wiring the DAO objects in the service beans, the exact error is:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ACLService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private pkg.service.UserServ pkg.service.ACLServ.userServ; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServ': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private pkg.repositories.UserDAO pkg.service.UserServ.userDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [pkg.repositories.UserDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
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:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at pkg.config.WebAppInit.onStartup(WebAppInit.java:35)
The application bootstrap start at WebAppInit.Java since it implements the WebApplicationInitializer interface, the web.xml code is:
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"></web-app>
The WebAppInit.Java code the onStartup method as:
public class WebAppInit implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context =
new AnnotationConfigWebApplicationContext();
context.register(ApplicationContextConfig.class);
context.refresh();
...
Then the ApplicationContextConfig class is annotated with #Configuration, code is:
#Configuration
#PropertySource("classpath:application.properties")
#ImportResource("classpath:*springDataConfig.xml")
#Import({BasicDataSourceConfig.class,PersistenceSpringDataJpaConfig.class})
#ComponentScan(basePackages={"pkg.service","pkg.utils"})
public class ApplicationContextConfig {
}
so this is only the main/entry point for the Java configuration, then it follow application.properties (Not included but just ask for it), then the springDataConfig.xml with code:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<repositories base-package="pkg.repositories" />
</beans:beans>
The BasicDataSourceConfig.Java configure the DataSource #Bean as:
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
...
The PersistenceSpringDataJpaConfig.Java configure the LocalContainerEntityManagerFactoryBean as:
#Configuration
public class PersistenceSpringDataJpaConfig {
...
#Autowired
DataSource dataSource;
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
...
The other files are not directly related, if I cut off the dependency removing/commenting the code:
#Autorire
private UserDAO userDAO
in the UserService class; the application runs without error, I mean besides the null pointer exception when accessing the dao object in the service bean.
So the question is: Why the Spring Data JPA does not create the userDAO bean?
PS: I did deliberately get rid from all #Transactions management to simplify it, besides it should work without transaction, isn't it?
Is it correct that one can create spring beans using just the #Component annotation as long as context component scanning is configured?
Using spring 3.0.5 with Java 6.
My test case is:
#ContextConfiguration(locations={"classpath:spring-bean.xml"})
public class ServerServiceUnitTest extends AbstractJUnit4SpringContextTests {
#Autowired
private ServerService serverService;
#Test
public void test_server_service() throws Exception {
serverService.doSomething();
//additional test code here
}
}
The spring-bean.xml file contains:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
</beans>
My class I want to be a bean is:
#Component("ServerService")
public class ServerServiceImpl implements ServerService {
private static final String SERVER_NAME = "test.nowhere.com";
//method definitions.....'
}
Should that not be sufficient for spring to instantiate the ServerService bean and do the autowiring?
The error I get is:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [serversystem.ServerService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I'm sure I'm missing something simple.
You have not defined in your spring-beans.xml the <context:component-scan> element:
<context:component-scan base-package="the.package.with.your.service"/>
The inclusion of
<context:annotation-config/>
only allows you to use #Required, #Autowired, and #Inject annotations for configuration. By specifying the <context:component-scan>, you are telling Spring where to look for #Component annotations.
if you are using annotated controllers and other features
you should include
<mvc:annotation-driven/>
you should use
<context:component-scan base-package="spring3.example.controllers"/>
to specify the package in which controller classes are stored.