Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

... is no accessor method

Tags:

java

spring

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 :)

like image 409
portux Avatar asked Dec 05 '16 10:12

portux


People also ask

Which of the following is not an accessor method?

doSomething() is no accessor method!

Is set an 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.

Is print an accessor method?

It's not an accessor, because it doesn't return a value (it's void ).

What are accessor methods in Java?

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.


1 Answers

You cannot autowire component that way, try this:

@Autowire AnInterface ai;

@RequestMapping("/hello")
public String something() {
    ai.doSomething();
    return "/";
}
like image 117
Jaiwo99 Avatar answered Sep 28 '22 08:09

Jaiwo99