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

猜你喜欢

转载自ximeng1234.iteye.com/blog/2233705
今日推荐