1、开发中出现的问题
在开发中,会对一个类加加上@Autowired注解,然后就可以使用这个类中的方法了,但是new 一个对象不也是可以的么? 这个问题经常在脑海中盘旋,但是一直没有深入研究过。
最近开发一个功能,使用new对象,代码报空指针异常了,当我把new的对象改成@Autowired 注入的方式后,代码就可以正常运行了。为什么呢?
问题复现
TestService 通过@Autowired注入,那么Spring容器就会自动注入TestService 中会用到的TestMapper
如果TestService 通过new对象方式新建的话,Spring容器就不会自动注入TestMapper,此时testMapper为null,会报空指针异常。
public class TestController {
@Autowired
private TestService testService;
@RequestMapping(value = "/testAutowired",method = RequestMethod.GET)
public void test() {
testService.test();
}
@RequestMapping(value = "/testNew",method = RequestMethod.GET)
public void test() {
TestService testService = new TestService ()
testService.test();
}
}
public class TestService {
@Autowired
private TestMapper testMapper;
public void test() {
testMapper.test();
}
}
2、@Autowired的定义
(1)spring创建对象
(2)spring注入属性。当我们在将一个类上标注@Service或者@Controller或@Component或@Repository注解之后,spring的组件扫描就会自动发现它,并且会将其初始化为spring应用上下文中的bean。 当需要使用这个bean的时候,例如加上@Autowired注解的时候,这个bean就会被创建。而且初始化是根据无参构造函数。
(3)@Autowired可以标注在属性上、方法上和构造器上,来完成自动装配。默认是根据属性类型,spring自动将匹配到的属性值进行注入,然后就可以使用这个对象的方法。
3、当标注的属性是接口时,其实注入的是这个接口的实现类
参考:Spring中@Autowired 注解的注入规则https://www.cnblogs.com/convict/p/10688335.html
优秀文章: