我得到“org.springframework.beans.factory.NoSuchBeanDefinitionException:没有名为'employee'的bean被定义”错误,我不确定我做错了什么。请在代码下方找到。使用AnnotationConfigApplicationContext的NoSuchBeanDefinitionException异常
)的AppConfig类:
@ComponentScan("com.spring.annotation.propertyconfigurer") @Configuration @PropertySource("classpath:employee.properties") public class AppConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } }
2)Employee类
@Component("employee")
public class Employee {
@Value("${emp.empId}")
private int empId;
@Value("${emp.name}")
private String name;
@Autowired
private Address address;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public void print() {
System.out.println("Employee Id -> " + empId);
System.out.println("Employee Name -> " + name);
System.out.println("Employee Address -> [ " + address.getCity() + "," + getAddress().getCountry() + "]");
}
}
3)地址类别:
@Component("address")
public class Address {
private String city;
private String country;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
4)麦类n级
public class PropertyConfigurerApp {
public static void main(String[] args) {
try (AbstractApplicationContext context = new AnnotationConfigApplicationContext("AppConfig.class")) {
Employee employee = (Employee) context.getBean("employee");
employee.print();
} catch (Exception e) {
e.printStackTrace();
}
}
}
请帮我解决这个问题。
感谢, 卡迈勒
@Massino我的AppCongif类已经有了ComponentScan。所以它应该工作。 –
另外,我使用@Component注册了Employee和Address类的spring bean。但是它仍然不起作用 –
你没有设置@ComponentScan({package-where-your-components-are})。你也不需要@ComponentScan(“com.spring.annotation.propertyconfigurer)豆 – Massimo