我想通过一个简单的程序来使用@Autowired注释Spring中的依赖注入 但我给我下面的错误@Autowired注解春天给我的NullPointerException
Exception in thread "main" java.lang.NullPointerException
at Customer.d(Customer.java:8)
at Main.main(Main.java:12)
通过xml配置它给我正确的结果。
我的XML文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="person" class="Person">
<property name="name" value="khan"/>
</bean>
<bean id="cust" class="Customer"></bean>
</beans>
Customer类
public class Customer {
@Autowired
private Person p;
public void display(){
System.out.println(p.getName());
}
}
Person类
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
主类
public class Main {
public static void main(String[] a) {
Resource r=new ClassPathResource("SpringXml.xml");
BeanFactory factory=new XmlBeanFactory(r);
Customer c=(Customer)factory.getBean("cust");
c.display();
}
}
而不是只提 “客户” 或 “人”,将其更改为CLASS = “complete-package-path.Customer”如果上面的类没有默认包 – Afridi
谢谢上面的类都是默认包 –
尝试在创建客户对象时使用ApplicationContext – Balasubramanian