byName Annotation based Autowiring (Spring3) - spring

I am trying to create spring-mvc project.
My "Repository" component is defined as
#Repository("testEntityDao")
public class TestEntityDaoImpl extends GenericDaoImpl<TestEntity> implements TestEntityDao {
"Service" component with instance of TestEntityDao
#Service("testManager")
public class TestManagerServiceImpl implements TestManagerService{
#Autowired
TestEntityDao testEntityDao;
TestManagerServiceImpl doesn't have any constructor defined and it also doesn't have getter and setter for testEntityDao. (I tried code after writing setter, but got same error).
ApplicationContext.xml has following line to enable autowiring byName
<beans xmlns="http://www.springframework.org/schema/beans"
.
.
default-autowire="byName">
<context:annotation-config />
<context:component-scan
base-package= .... />
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Error that I am getting is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.test.cms.dao.TestEntityDao com.test.cms.service.impl.TestManagerServiceImpl.testEntityDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.test.cms.dao.TestEntityDao] 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), #org.springframework.beans.factory.annotation.Qualifier(value=testEntityDao)}
How to resolve this error ?

Just refer to common parent package instead of all these packages. Make your component scan as:
<context:component-scan base-package="com.test.cms"/>

Related

How to autowire a service and a repository together

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.

How do I autowire my webservices client in my WAR application (using Spring)?

I’m using Maven 3.0.3, CXF 2.7.15, and Spring 3.2.11.RELEASE. Using the JAX-WS Maven plugin, web service client classes are auto-generated (plugin code below) ...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<wsdlDirectory>${basedir}/src/wsdl</wsdlDirectory>
<sourceDestDir>${basedir}/src/main/java</sourceDestDir>
<packageName>org.collegeboard.bsorg</packageName>
</configuration>
</execution>
</executions>
</plugin>
which include the below
package org.myproject.bsorg;
/**
* This class was generated by the JAX-WS RI.
* JAX-WS RI 2.1.3-b02-
* Generated source version: 2.1
*
*/
#WebService(name = "OrganizationWebService", targetNamespace = "http://mainco.org/bsorg/")
#XmlSeeAlso({
ObjectFactory.class
})
public interface OrganizationWebService {
Then I have my own service class, in which I try and reference the above through auto wiring …
package org.mainco.subco.myproject.service;
#Service("orgWsdlSvc")
public class OrgWsdlServiceImpl implements OrgWsdlService
{
#Autowired
private OrganizationWebService m_ows;
When I deploy my WAR file, I get the error
09:20:17,846 ERROR [org.springframework.web.context.ContextLoader] (MSC service thread 1-14) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orgWsdlSvc': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.mainco.bsorg.OrganizationWebService org.mainco.subco.myproject.service.OrgWsdlServiceImpl.m_ows; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.mainco.bsorg.OrganizationWebService] 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:290) [spring-beans-3.2.11.RELEASE.jar:3.2.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1148) [spring-beans-3.2.11.RELEASE.jar:3.2.11.RELEASE]
But I’m confused about how to properly autowire things in my web.xml and accompanying context files. In my WEB-INF/web.xml, I have
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/META-INF/spring/applicationContext-myproject.xml,
classpath:/META-INF/spring/infrastructure.xml
</param-value>
</context-param>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>myproject.webapp</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
In my WEB-INF/dispatcher-servlet.xml file I have
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<context:component-scan base-package="org.mainco" />
<!-- Define spring bean for use with this app. -->
<bean id="localPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:application.properties</value>
</property>
</bean>
<!-- Define application properties for use in Spring classes -->
<util:properties id="applicationProperties" location="classpath:application.properties" />
<tx:annotation-driven />
and in my “applicationContext-myproject.xml”, I have
<util:properties id="applicationProperties" location="classpath:application.properties" />
<util:properties id="coreProperties" location="classpath:core.properties" />
<context:component-scan base-package="org.mainco.subco" />
<context:component-scan base-package="org.mainco.bsorg" />
<bean id="sessionTimeoutInSeconds" class="java.lang.Long">
<constructor-arg>
<value>3600</value>
</constructor-arg>
</bean>
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<!-- Define spring bean for use with this app. -->
<bean id="localPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:application.properties</value>
</property>
</bean>
<bean id="assert" class="org.mainco.subco.util.Assert" factory-method="createInstance" />
<http-conf:conduit name="https://.*">
<http-conf:tlsClientParameters secureSocketProtocol="TLSv1" disableCNCheck="true">
<sec:trustManagers>
<sec:keyStore type="JKS" password="${key.store.password}" resource="${key.store.file}" />
</sec:trustManagers>
<sec:keyManagers keyPassword="${key.manager.password}">
<sec:keyStore type="pkcs12" password="${private.key.password}" resource="${private.key.file}" />
</sec:keyManagers>
</http-conf:tlsClientParameters>
</http-conf:conduit>
<jaxws:client id="orgWebServiceClient"
serviceClass="org.mainco.bsorg.OrganizationWebService"
address="${wsdl.url}"
/>
<bean id="organizationWebService" class="org.mainco.bsorg.OrganizationWebService"></bean>
What do I need to do so I can autowire my web services client?
Edit: Per the suggestion given, I added the bean definition to my application context (see above) file, but received the following error upon deplyohing the application:
Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'orgWsdlSvc': Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.myproject.bsorg.OrganizationWebService org.mainco.subco.myproject.service.OrgWsdlServiceImpl.m_ows;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'organizationWebService' defined in class path resource [META-INF/spring/applicationContext-myproject-mvc.xml]: Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.mainco.bsorg.OrganizationWebService]: Specified class is an interface
You are missing the bean definition in your applicationContext-myproject.xml.
<!-- Definition for OrganizationWebService bean -->
<bean id="organizationWebService" class="org.mainco.bsorg.OrganizationWebService"></bean>
See this for more examples:
http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/
EDIT:
You are making progress. Now spring is able to find the autowired candidate in the application context.
However, there is another problem, the candidate is an interface and spring is not able to instantiate it (neither does javac). So, you need to create a class to implement your interface and describe it in your application context (instead or describing an interface). So; you need to create a org.mainco.bsorg.OrganizationWebServiceImp class implementing org.mainco.bsorg.OrganizationWebService and change your application context to:
<bean id="organizationWebService" class="org.mainco.bsorg.OrganizationWebServiceImp"></bean>
More info here: Could not instantiate bean class: Specified class is an interface
EDIT2:
Look at https://jax-ws.java.net/2.2.1/docs/UsersGuide.html#3.1.2_Starting_from_a_WSDL_File
The documentation clarifies that:
Generate a service endpoint interface.
Implement the service endpoint interface.
Create a WAR file to deploy.
You need to implement the service endpoint interface with a concrete class eg: OrganizationWebServiceImp

Could not autowire jaxrs client

I have this in my applicationContext.xml (I am using http://cxf.apache.org/jaxrs)
<context:annotation-config />
<context:component-scan base-package="br.com.test" />
<bean id="jsonProvider" class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" />
<jaxrs:client id="testClient"
serviceClass="br.com.test.ws.InterfaceServiceTest"
address="http://localhost:8080/ocs-teste-ws-web/services/myservice">
<jaxrs:providers>
<ref bean="jsonProvider" />
</jaxrs:providers>
</jaxrs:client>
I am including the jar with interface in this project but I am getting the following exception:
1318 [localhost-startStop-2] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someBeanImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: br.com.test.ws.InterfaceServiceTest br.com.test.impl.SomeBeanImpl.interfaceServiceTest; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [br.com.test.ws.InterfaceServiceTest] 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)}
What am I doing wrong?
Thanks.
Don't use #Autowired, use #Resource instead, in the class where you are trying to inject your client.
Because #Autowired and #Inject
1) Matches by Type
2) Restricts by Qualifiers
3) Matches by Name
And #Resource
1) Matches by Name
2) Matches by Type
3) Restricts by Qualifiers (ignored if match is found by name)
In your case you use a proxy, So the class type isn't what you want. With #Resource you start by find by name.

Starting asynchronous task via Spring TaskScheduler

I need to execute a task at 7.05am but I am getting an error.
This is the Controller I created.
#Service("myCtr")
public class MyController {
#Autowired
private TaskScheduler scheduler;
#Async
public void executeTaskT() {
scheduler.schedule(new MyWorker(),
new CronTrigger("5 7 * * *"));
}
}
MyWorker is implementing Runnable simply this way:
[...]
#Override
public void run() {
doWork();
}
private void doWork() { [...]
My scheduler configuration file is imported by the web-application-config.xml:
<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-3.1.xsd">
<bean id="TaskScheduler"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<property name="waitForTasksToCompleteOnShutdown" value="true" />
<property name="poolSize" value="1000" />
</bean>
</beans>
The error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyCtr': Injection
of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private
org.springframework.scheduling.TaskScheduler [...].MyController.scheduler; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type
[org.springframework.scheduling.TaskScheduler] 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)}
[...]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private
org.springframework.scheduling.TaskScheduler [...].MyController.scheduler; nested
exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type
[org.springframework.scheduling.TaskScheduler] 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)}
[...]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type
[org.springframework.scheduling.TaskScheduler] 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)}
It appears that Spring can't find your TaskScheduler bean.
With INFO logging, you should be able to find your bean definition in the log during initialization. If not, make sure your configuration file is effectively read by doing further tests.
For your precise need, you can also use the following:
#Service
public class MyService {
#Scheduled(cron = "0 5 7 * * *")
public void myMethod() { ... }
}
With this configuration:
<task:annotation-driven scheduler="myScheduler"/>
<task:scheduler id="myScheduler" pool-size="1000"/>
And assuming MyService is properly seen as a bean, using e.g. Component Scan.

Autowiring request scoped beans into application scoped beans

Is it possible to autowire a request scoped bean into an application scoped bean. i.e
I have a class RequestScopedBean:
class RequestScopedBean {
....
....
....
}
and a class Application scoped bean in which the request scoped bean is autowired.
class ApplicationScopedBean {
#Autowire
private RequestScopedBean requestScopedBean;
....
....
....
}
and the spring-config xml is as follows:
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
">
<bean id="applicationScopedBeans" class="ApplicationScopedBean" />
<bean id="requestScopedBean" class="RequestScopedBean" scope="request">
</bean>
</beans>
when I try to run this application the bean creation of applicationScopedBean fails with the following error:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ApplicationScopedBean': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private RequestScopedBean requestScopedBean; nested exception is java.lang.IllegalStateException: No Scope registered for scope 'request'
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
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.doGetBean(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1075)
at com.amazon.coral.reflect.instantiate.SpringInstantiatorFactory$1.newInstance(SpringInstantiatorFactory.java:168)
... 19 more
You have to mark your requestScopedBean as a scoped proxy also, this way Spring will inject in a proxy for requestScopedBean and in the background manage the scope appropriately.
<bean id="requestScopedBean" class="RequestScopedBean" scope="request">
<aop:scoped-proxy/>
</bean>
More here
The exception above suggests that you have not correctly configured Spring for the provision of request scoped beans.
You need to add this to your web.xml as described in the docs here:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
However, there is more to your question than just configuration. You are attempting to inject a request scoped bean into a singleton scoped bean. Spring resolves dependencies and instantiates singletons when the DI container starts. This means that ApplicationScopedBean will only be created once (at this point there will be no request in flight and so the autowiring will most likely fail).
If you were using a prototype scoped bean instead of request scoped you'd have to consider a way of suppling the singleton scoped bean with a fresh instance everytime it was used. The approaches for this are described in the Method Injection chapter of the Spring docs.
#Airwavezx the annotation equivalent is the followinng:
#Scope( value = SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS )

Resources