@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 findAll(){
List retList = new ArrayList();
for(int i=1;i<10;i++){
retList.add("test"+i);}return retList;}
}//加入Spring Pool
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 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 proxysay:This is save for test spring
参考: