@autowired注入失敗_@Autowired注入值為空怎麼辦
阿新 • • 發佈:2021-01-31
技術標籤:@autowired注入失敗
練習spring時發現Autowired注入值為空
/** 介面 **/ public interface UserService { public void save(); } /** 實現類 **/ package com.zzr.demo.service; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Service("service") public class UserServiceImpl implements UserService{ @Override public void save() { System.out.println("業務邏輯程式碼"); } }
applicationContext.xml
<!--註解掃描開啟--> <context:component-scan base-package="com.zzr.demo"/> <!-- <bean id="service" class="com.zzr.demo.service.UserServiceImpl"/>--> <bean id="myXmlAspects" class="com.zzr.demo.aspects.MyXmlAspects"/> <aop:config> <!--配置切面--> <aop:aspect ref="myXmlAspects"> <!--五種通知型別 aop:before:前置通知,目標方法執行前,執行增強方法 aop:after:最終通知,目標方法執行後,無論成功或失敗必執行 aop:after-reterning:後置通知,目標方法執行成功後,執行增強方法 aop:after-throwing:異常通知,目標方法執行失敗後,執行增強方法 aop:around:環繞通知,目標方法執行前後,都可以進行增強,目標物件的方法需要手動執行--> <aop:before method="log" pointcut="execution(public void com.zzr.demo.service.UserServiceImpl.save())"/> </aop:aspect> </aop:config>
切面類,應該跟這個沒關係,但是還是貼出來吧
public class MyXmlAspects { //模擬實現日誌 public void log(){ System.out.println("通知執行"); } public void arroundLog(ProceedingJoinPoint point){ try { System.out.println("目標方法執行前"); point.proceed(); System.out.println("目標方法執行後"); } catch (Throwable throwable) { throwable.printStackTrace(); }finally { System.out.println("xxx"); } } }
測試類
public class Test1 {
public UserService getService(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService service = (UserService) ac.getBean("service");
return service;
}
@Test
public void run1(){
UserService service = this.getService();
service.save();
}
// @Resource
@Autowired
// @Qualifier("service")
private UserService service;
@Test
public void run2(){
service.save();
}
}
run1()是成功的,run2()會出現空指標,resource和qualifier都試過了沒用,怎麼辦求指導
run1()執行結果
run2()執行結果
很多帖子部落格上都說是因為使用了new物件,可是我也沒有用啊。那是為什麼呀,各位大佬幫幫孩子吧。
問題已解決,忘記啟動IOC容器這件事了,我配置了前端控制器啟動時載入spring問題解決。文章不刪,釘在恥辱柱上。