new出來的物件無法呼叫@Autowired注入的Spring Bean
阿新 • • 發佈:2019-01-24
@Autowired注入Spring Bean,則當前類必須也是Spring Bean才能呼叫它,不能用new xxx()來獲得物件,這種方式獲得的物件無法呼叫@Autowired注入的Bean。
1、類1,加入Spring Pool
public class PersonServiceImpl implements PersonService{ public void save(){ System.out.println("This is save for test spring"); } public List<String> findAll(){ List<String> retList = new ArrayList<String>(); for(int i=1;i<10;i++){ retList.add("test"+i); } return retList; } } //加入Spring Pool <bean id="personServiceImpl" class="com.machome.testtip.impl.PersonServiceImpl" > </bean>
2、類2,@Autowired類1,並且也加入Spring Pool
public class ProxyPServiceImpl implements ProxyPService { public void save(){ System.out.print("this is proxy say:"); personService.save(); } public List<String> findAll(){ System.out.print("this is proxy say:"); return personService.findAll(); } @Autowired PersonService personService; }
3、直接new類2,則執行其方法時出null pointer錯誤
ProxyPService proxyPService = new ProxyPServiceImpl(); proxyPService.save(); 執行報錯: java.lang.NullPointerException at com.machome.testtip.impl.ProxyPServiceImpl.save(ProxyPServiceImpl.java:18) at com.machome.testtip.TestSpring2.testSave(TestSpring2.java:34) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
4、解決:用Spring方式獲取類2的Bean,再執行其方法,沒問題
ProxyPService proxyPService = null; try { String[] confFile = {"spring.xml"}; ctx = new ClassPathXmlApplicationContext(confFile); proxyPService = (ProxyPService)ctx.getBean("ProxyPServiceImpl"); } catch (Exception e) { e.printStackTrace(); } proxyPService.save(); 執行: this is proxy say:This is save for test spring
參考: