new和@Autowired的區別
阿新 • • 發佈:2020-08-15
-
controller層:
@RequestMapping("/payment") @RestController public class WxPayController { public WxPayServiceImpl wxPayService = new WxPayServiceImpl(); @RequestMapping("/wxpay/{product_id}") public String getWxQrCode(@PathVariable("product_id") Integer productId) { System.out.println(productId); return wxPayService.getWxQrCode(productId); } }
service層:
@Service public class WxPayServiceImpl implements WxPayService { @Autowired public WxPayConfigBean wxPayConfigBean; @Override public String getWxQrCode(Integer productId) { System.out.println("wxPayConfigBean:" + wxPayConfigBean); HashMap<String, String> map = new HashMap<String,String>(); map.put("appid",wxPayConfigBean.getAppID()); map.put("mch_id",wxPayConfigBean.getMchID()); //這裡獲得的是以秒為單位的時間戳 Long timeStamp = WXPayUtil.getCurrentTimestamp(); map.put("time_stamp",timeStamp.toString()); map.put("product_id",productId.toString()); try { map.put("sign",WXPayUtil.generateSignature(map,wxPayConfigBean.getKey())); } catch (Exception exception) { exception.printStackTrace(); } String str = "//wxpay/bizpayurl?" + "sign=" + map.get("sign") + "&appid=" + map.get("appid") + "&mch_id= " + map.get("mch_id") + "&product_id=" + map.get("product_id") + "&time_stamp=" + map.get("time_stamp") + "&nonce_str=" + map.get("nonce_str"); return JsonUtil.ajaxReturn(str); } }
測試該介面可以發現:
wxPayConfigBean:null
,顯然即便這裡用了@Autowired但還是注入失敗了.然是如果我們通過junit直接測試:@Autowired public WxPayConfigBean wxPayConfigBean; @Test void contextLoads() { System.out.println(wxPayConfigBean.toString()); }
此時,資料注入又是成功的.
-
查詢了比較多的資料後我突然明白自己對於new和@Autuwired的理解還是有很大問題.new建立了一個新物件,但Autowired不是,它是通過先匹配型別再匹配名字
@RequestMapping("/payment") @RestController public class WxPayController { @Autowired public WxPayServiceImpl wxPayService; @RequestMapping("/wxpay/{product_id}") public String getWxQrCode(@PathVariable("product_id") Integer productId) { System.out.println(productId); return wxPayService.getWxQrCode(productId); } }