......不是访问方法

时间:2016-12-05 10:25:53

标签: java spring

我正在学习春天的绳索 我尝试 autowire 一个方法参数,如下所示:

@RequestMapping("/hello")
public String something(@Autowire AnInterface ai) {
    ai.doSomething();
    return "/";
}

使用以下接口和类:

@Component
public interface AnInterface {
    void doSomething();
}

@Component
public class Implementation implements AnInterface {
    @Autowired private AnotherInterface ai;

    public Implementation() { ; }

    public Implementation(AnotherInterface ai) {
        this.ai = ai;
    }

    public void setAi(AnotherInterface ai) {
        this.ai = ai;
    }

   @Override
   public void doSomething() {
       System.out.println(ai.hello());

   }
}

@Component
public interface AnotherInterface {
    String hello();
}

@Component
public class AnotherImplementation implements AnotherInterface {

    @Override
    public String hello() {
        return "hello";
    }

}

然而,在调用控制器的方法时,我得到IllegalArgumentException
Invoked method public abstract void AnInterface.doSomething() is no accessor method!

我做错了什么?

提前致谢:)

1 个答案:

答案 0 :(得分:2)

你无法以这种方式自动装配组件,试试这个:

@Autowire AnInterface ai;

@RequestMapping("/hello")
public String something() {
    ai.doSomething();
    return "/";
}