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

原文地址:https://www.cnblogs.com/EasonJim/p/7580158.html