I'm currently learning the ropes of Spring.
I tried to autowire a method parameter like so:
@RequestMapping("/hello")
public String something(@Autowire AnInterface ai) {
ai.doSomething();
return "/";
}
With the following interfaces and classes:
@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";
}
}
However, when calling the controller's method, I get an IllegalArgumentException
:Invoked method public abstract void AnInterface.doSomething() is no accessor method!
What am I doing wrong?
Thanks in advance :)
doSomething() is no accessor method!
Accessor methods, also called get methods or getters, allow a way to get the value of each instance variable from outside of the class. In the next lesson, we will see mutator methods, also called set methods or setters, that allow a way to change the values of the instance variables.
It's not an accessor, because it doesn't return a value (it's void ).
In Java, accessor methods return the value of a private variable. This gives other classes access to that value stored in that variable. without having direct access to the variable itself. Accessor methods take no parameters and have a return type that matches the type of the variable they are accessing.
You cannot autowire component that way, try this:
@Autowire AnInterface ai;
@RequestMapping("/hello")
public String something() {
ai.doSomething();
return "/";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With