Resource resource=new ClassPathResource("bean.xml");
BeanFactory factory=new XmlBeanFactory(resource);
AccountServiceImpl accountService= (AccountServiceImpl) factory.getBean("accountservice");
accountService.helloworld()
用了这个XmlBeanFactory这个类时如果使用注解调用,使用@Autowired进行注入bean容器的对象,调用与此相关的方法时就会报出:
Exception in thread “main” java.lang.NullPointerException
@Component(value = "accountservice")
public class AccountServiceImpl implements AccountService {
@Autowired
private User user;
public void helloworld() {
System.out.println(user);
user.helloworld();
}
}
解决方法为
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//根据id获取bean对象
AccountServiceImpl accountService= (AccountServiceImpl) ac.getBean("accountservice");
accountService.helloworld();