new 出的对象,无法调用@Autowired进入的spring bean

来源:互联网 发布:金山数据恢复软件多大? 编辑:程序博客网 时间:2024/05/18 20:06


原文出处:http://blog.sina.com.cn/s/blog_6151984a0100oy98.html


@Autowired来的spring 下的bean,则当前类必须也是spring bean才能调用它,不能用new Xxx()来获得对象,这种方式获得的对象无法调用其内的@autowired的bean


1. 类1
加入spring poolpublic 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 poolpublic 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"};

                ApplicationContextctx = 

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
原创粉丝点击