Reputation: 33
It is a very simple program that has a main class as JavaLoader
, one interface Student
. Student
is implemented by two classes.
I have also made a configuration class. When I instantiate the bean from the main class and call a method on Samir
. A NoSuchBeanDefinitionException
is thrown.
Main class (JavaLoader
):
package spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class JavaLoader {
public static void main(String[] args) {
AnnotationConfigApplicationContext appContext = new
AnnotationConfigApplicationContext("StudentConfig.class");
Student samir = (Student) appContext.getBean("samir", Student.class);
System.out.println(samir.readsBook());
}
}
StudentConfig
class:
package spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("spring")
public class StudentConfig {
}
Samir
class:
package spring;
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.Component;
@Component("samir")
public class Samir implements Student{
@Autowired
@Qualifier("history")
Book book;
public Samir(Book book){
this.book = book;
}
public String readsBook(){
return book.readBook();
}
}
The expected output is that the method samir.readsBook()
on JavaLoader
should be executed
Upvotes: 3
Views: 1183
Reputation: 27585
You need to provide a Class
instance to the AnnotationConfigApplicationContext
constructor:
new AnnotationConfigApplicationContext(StudentConfig.class);
note that StudentConfig.class
is not the same as the string "StudentConfig.class"
.
Note that AnnotationConfigApplicationContext
has a string-constructor as well (that's why your code still compiles), but that string is interpreted as a base package for auto-scanning rather than the configuration class name.
Upvotes: 4