Spring中的@Autowired和@Bean有什么区别?
@Autowired
@Autowired用于注入bean,前提是这个bean要注册在spring容器中,通过@Component、@Service、@Controller、@Repository、@Configration等注解可以将bean注册到spring容器中,然后通过@Autowired、@Resource或者@RequiredArgConstructor可以从容器中拿出bean使用。
@Autowired、@Resource、@RequiredArgsConstructor有什么区别?
@Autowired是spring提供的注解,@Resource是JDK提供的注解,而@RequiredArgsConstructor是Lombok提供的注解。
@Autowired按照类型注入bean,如果spring容器中不存在此类型的bean,会报错,可以搭配@Qulifier来按照name注入bean。
@Resource先按照name注入bean,如果name不存在,再根据类型来注入bean。
@Autowied和@Resource可以在字段、方法、构造器上使用,在字段上使用是字段注入,通过反射实现;在方法上使用是setter注入;在构造器上使用是构造注入。而@RequiredArgsConstructor是在类上使用的,会自动给final修饰的变量生成构造器,从而构造注入使用。
@Bean
@Bean是用于注册bean的,@Component是用于注册我们自己定义的bean,将自定义的bean注册到spring容器中,而对于Maven导入的一些第三方jar包要注册到spring中就需要使用@Bean注解了,@Bean注解用于方法上,在这个方法中我们产生对象,这个对象就会注册到容器中。