new出來的對象無法調用@Autowired注入的Spring Bean


@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

 

參考:

http://blog.sina.com.cn/s/blog_6151984a0100oy98.html

https://segmentfault.com/q/1010000008200816

http://www.cnblogs.com/chyu/p/4655475.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM