I've been modifying my class to avoid new
operator on StudentService
( let Spring's container manages it) there in my controller. I need Student student;
field there gets injected with StudentService
but rather than getting the student
injected it gets injected with an exception saying :
No qualifying bean of type [com.Student] is defined: expected single matching bean but found 2: studentService,ss
I want this program to print
NAME : bravo
Student :
package com;
public interface Student {
public String getN();
}
StudentService :
package com;
import org.springframework.stereotype.Service;
@Service
public class StudentService implements Student{
String name;
@Override
public String getN() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Controller
package com;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TheController {
@Autowired
private ApplicationContext appContext;
@Autowired
Student student;
@RequestMapping("/")
public String aMethod() {
StudentService ss = (StudentService) appContext.getBean("ss");
ss.setName("bravo");
System.out.println("NAME : " + student.getN());
// while "NAME : " + ss.getN() will work, of course
return "";
}
}
dispatcher-servlet
...
<context:component-scan base-package="com" />
...
<bean id="ss" class="com.StudentService" />
...
EDIT : If I do this :
@Service ("st")
public class StudentService implements Student{
and this (in controller)
@Autowired
@Qualifier("st")
Student student; // tipenya interface
no exceptions, but it produces
NAME :null
If I get rid of the @Service
and load StudentService
as <bean class="com.StudentService".. >
and load it manually through application context then it will work.
I mean how is that @Service
can't be autowired