0

I have an oracle database and using mybatis as the persistence layer. I am also using a mapper interface to get my database calls. I have a worker class that calls the mapper. Inside that worker class, I have declared a private variable with the @Resource annotation. Without specifying a @Service annotation anywhere it seems to work. I am unable to figure out why. I have went through the configuration files and don't see any mention of the class anywhere.

mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.test.TestMapper">
<select id="getAll">
select * from MY_DB
</select></mapper>

TestMapper.java

package com.test;
import com.test.domain.Entity
public interface TestMapper {
    List<Entity> getAll();
}

TestWorker.java

import com.test.TestMapper;
package com.test
public class TestWorker {
    @Resource(name = "testMapper")
    private TestMapper testMapper;

    public List<Entity> getEverything() { 
        return testMapper.getAll(); 
    }
}

With this, I can call the getEverything() fine. It will return all the entries in my database. A minor problem I have is that Intellij keeps on keeps on yelling me that no bean is found. Which also makes sense as there is nothing else named "testMapper".

If I remove @Resource(name="testMapper"), the code will run and compile but it will have a null exception when calling the function.

Finally, after keeping @Resource(name="testMapper") and adding @Service("testMapper") in the TestMapper interface everything is fine. Intellij doesn't complain and the code runs as expected.

Now my question is, originally how does spring inject TestMapper into the testMapper is the TestWorker class?

TheBlueMan
  • 316
  • 1
  • 4
  • 27
  • curious, does it still work if you `@Autowire` instead of `@Resource`? what servlet container implementation are you using (tomcat? jboss?)? I would think this should't work, but `@Resource` is processed differently from `@Autowire` and Spring can do type based injection, so it could see the type and figure it out, but I would think that it shouldn't. Yet I'm not sure if perhaps `@Resource` will get injected without annotation. May also be helpful to know what consumes TestWorker. – xenoterracide Jul 14 '16 at 01:24
  • 1
    Check here[@Resource vs @Autowired](http://stackoverflow.com/questions/4093504/resource-vs-autowired) – Blank Jul 14 '16 at 03:16
  • Could you please add spring context where your create datasource and sessionfactory? – Ivan Lymar Jul 14 '16 at 06:29
  • Ah, ok. I've been trying to look through the documentation to see an explanation and I see `@Resource` falls back to `@Autowired` if it can't find a name. Thanks guys for the help. – TheBlueMan Jul 14 '16 at 12:54

0 Answers0