Could not autowire jaxrs client - spring

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.

Related

Dependency injection with Spring not working when using nested beans

I'm trying to use Spring and have a trouble using it for a case.
I have the following code:
<util:map id="someMap" value-type="java.util.Set">
<entry key="a" value-ref="setA"/>
<entry key="b" value-ref="setB"/>
</util:map>
<util:set id="setA">
<value>A</value>
</util:set>
<util:set id="setB">
<value>B</value>
</util:set>
with the following Java code (using #Qualifier to get "someMap"):
package a.b.c;
public class SomeClass {
private final Map<String, Set<String>> someMap;
#Autowired
public SomeClass(#Qualifier("someMap") final Map<String, Set<String>> someMap) {
this.someMap = someMap;
}
}
and it's giving me the following error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'a.b.c.SomeClass': Unsatisfied dependency expressed through constructor argument with index 2 of type [java.util.Map]: : No matching bean of type [java.util.Set] found for dependency [map with value type java.util.Set]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:{#org.springframework.beans.factory.annotation.Qualifier(value=someMap)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [java.util.Set] found for dependency [map with value type java.util.Set]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=someMap)}
Looks like it's having trouble finding the Set but I don't know why it's happening. How would you solve this problem?
I found how to fix this issue. I had to use #Value("#{#someMap}") instead of #Qualifier("someMap").
I hope you are using spring 4.3 or above version
Try with adding mapclass,key-type
<util:map id="AdditionalParams" map-class="java.util.HashMap"
key-type="java.lang.String" value-type="java.lang.String">

Spring beans GeoModule bean injection to RepositoryRestMvcConfiguration

I'm currently testing spring data rest, and I want to expose the primary keys (ids) of my entities through the REST interface.
I have found that the proper (?) way to do this is:
public class IdExporterConfiguration extends RepositoryRestMvcConfiguration {
#Override
protected void configureRepositoryRestConfiguration(
RepositoryRestConfiguration config) {
super.configureRepositoryRestConfiguration(config);
config.exposeIdsFor(User.class);
}
}
The problem is, that if I change my bean definition to this:
<bean class="test.project.util.IdExporterConfiguration"/>
From this:
<bean class="org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration"/>
my application fails to start...
The error is:
Could not autowire field: org.springframework.data.geo.GeoModule org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration.geoModule;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.data.geo.GeoModule] 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)}
Basically it says that it does not find a GeoModule bean, so it can't autowire it for the RepositoryRestMvcConfiguration base...
Now the fun part is, that is I define the bean:
<bean class="org.springframework.data.geo.GeoModule"/>
The error changes to:
Could not autowire field: org.springframework.data.geo.GeoModule org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration.geoModule;
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.data.geo.GeoModule] is defined:
expected single matching bean but found 2: jacksonGeoModule,org.springframework.data.geo.GeoModule#0
So if I don't define a bean, there is 0, but if I define one, there is 2?
I still don't know why, but if I use the #Configuration annotation, then it works...
No GeoModule bean needed, but how can it be, that with the original config as XML bean definition it works, but with the subclass, it does not?

Failed to load ApplicationContext in JUnit with JNDI datasource

I have some troubles testing my application, whereas it works well in normal execution.
I think it comes from JNDI resources which are not found, but I don't understand why and how to fix it.
When I start my Junit test, I got this error:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at ...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'DAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource com.sample.DAOImpl.myDatasource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] 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=myDatasource)}
Related cause: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDatasource' defined in URL [file:src/test/resources/spring/test-dao-config.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)
at ...
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource com.sample.DAOImpl.myDatasource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] 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=myDatasource)}
at ...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] 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=myDatasource)}
at ..
Here is my configuration:
Context.xml
<Resource name="jdbc/myDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#database:99999:instance"
username="user"
password="password"
validationQuery="select 1 from dual"
testOnBorrow ="true"
maxActive="5"
maxIdle="1"
maxWait="-1" />
test-dao-config.xml
<bean id="myDatasource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/myDatasource" />
</bean>
DaoImpl
#Repository
public class DacsDAOImpl implements DacsDAO
{
private final static Logger LOGGER = LoggerFactory.getLogger(DAOImpl.class);
#Autowired
#Qualifier("myDatasource")
private DataSource myDatasource;
....
}
And my tests
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/test/resources/spring/test-dao-config.xml" })
public class MyDAOImplTest
{
private MyDAO dao;
#BeforeClass
public static void initJndi() throws IllegalStateException, NamingException
{
//some test, but doesn't work
// SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
// builder.bind("java:comp/env/jdbc/myDatasource", "myDatasource");
// builder.activate();
}
#Before
public void setUp() throws IllegalStateException, NamingException
{
dao = new MyDAOImpl();
}
#Test
public void testTotalUser()
{
int result = dao.getTotalUser();
Assert.assertEquals(0, result);
}
}
Thanks
You are running in a test case so everything in your Context.xml isn't available as that is only available on tomcat. Why do you need a jndi lookup in your test case anyway? If you want to test your dao use an in-memory database like hsql, h2 or derby and use that instead. Spring has some nice tags to make it easy for you.
<jdbc:embedded-database id="myDataSource" type="H2">
// Add some init scripts here.
</jdbc:embedded-database>
If you really need to do a JNDI lookup you are almost there in your test case. However you have to register a DataSource not a String. So you still will need to construct some (in-memory) datasource and bind that to the mock jndi location
#BeforeClass
public static void initJndi() throws IllegalStateException, NamingException
{
//some test, but doesn't work
// Construct in-memory database
SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
builder.bind("java:comp/env/jdbc/myDatasource", myDatasource); //Actual datasource not a String!
builder.activate();
}
And finally your test is also flawed, you are loading your context but aren't doing anything with it. You are constructing a MyDAOImpl in your #Before method. Why even bother loading the context as you are doing nothing with.

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.

Spring: how to ignore #Autowired property if bean is not defined

Situation: I have I class with property annotated with #Autowired:
public class MyClass {
#Autowired
protected MyAutoWiredBean myAutowiredBean;
}
Is there any possibility to made wiring this bean optional, i.e. if such bean is defined in some configuration file - to wire it, but if such bean is not defined - just continue working without throwing:
org.springframework.beans.factory.BeanCreationException:
Could not autowire field: protected MyAutoWiredBean...;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No matching bean of type [com.mypackage.MyAutoWiredBean] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
Have you tried:
#Autowired(required=false)
Javadoc:
Declares whether the annotated dependency is required. Defaults to true
you can set required attribute like :
#Autowired(required=false)
http://static.springsource.org/spring/docs/2.5.5/api/org/springframework/beans/factory/annotation/Autowired.html

Resources