问题:
@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 Bean容器中 <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; } ```java 3、直接new类2,则执行其方法时出null pointer错误 > 在使用spring框架注解的时候,不能在通过new关键字去实例化全局变量。如果两者并存的情况下,spring注入对象会失败,相应的引用会为空,后台就会报空指针异常
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
一般的话这属于一个特殊场景,如果需要的话就获取它的bean即可,但是现在springboot已经封装好了所以不必要管这些,遵从开发规则。