1. 程式人生 > >new 出的物件無法使用 @Autowired裝配進來的屬性,會報null

new 出的物件無法使用 @Autowired裝配進來的屬性,會報null

new 出的物件,無法呼叫@Autowired進入的spring bean

(2011-02-11 17:55:54) 轉載 @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