我得到「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