问题:
    java使用main方法作为入口,测试service时,发现使用
    
     @Autowired
    
    注入,总是报
    
     java.lang.NullPointerException
    
    异常
   
原因:
new出来的thread不在spring的容器中,所以无法注入成功,获得bean
解决:
ApplicationContext springUtilContext = new ClassPathXmlApplicationContext(“classpath:applicationContext.xml”);
    PaymentService paymentService=(PaymentService) springUtilContext.getBean(
    
     PaymentService.class
    
    );
   
代码如下:
package com.upincar.xigua.payment.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.upincar.xigua.customer.entity.CustomerInfo;
import com.upincar.xigua.payment.service.PaymentService;
import net.sf.json.JSONObject;
public class Test {
	ApplicationContext  springUtilContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
			
	public static void main(String[] args) {
		new Test().test();
	}
	
	public void test(){
		Map<String, String> paramMap=new HashMap<>();
		try {
			paramMap.put("token", "974729c60f5c4c3085390db9bb15b83c");
			paramMap.put("paymentType", "XCX-2");
			paramMap.put("sumPrice", "1");
			paramMap.put("openid", "okHCp5TURl7KcgoeUIe1-BOfkSBo");
			CustomerInfo customerInfo=new CustomerInfo();
			customerInfo.setId(1);
			customerInfo.setAccount("17521010129");
			customerInfo.setName("zora");
			PaymentService paymentService=(PaymentService) springUtilContext.getBean(PaymentService.class);
			JSONObject result =  paymentService.balancePay(customerInfo, paramMap);
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
版权声明:本文为qq_42714869原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。