使用<context:component-scan>时@Autowired是否必须配合@Component?无@Component能否生效?
关于@Autowired与@Component的关系解答
嘿,咱们把@Autowired和@Component之间的这点事儿掰扯清楚——你的两个问题本质上是同一个,我来给你拆解明白:
核心逻辑先理清
@Autowired的作用是让Spring从容器中取出匹配的Bean,注入到指定的字段、构造方法或方法中;而**@Component**(包括它的衍生注解@Controller、@Service、@Repository)是告诉Spring「把这个类纳入容器管理,生成对应的Bean实例」的方式之一。
结论:@Autowired不必强制搭配@Component使用
只要你要注入的对象已经是Spring容器管理的Bean,@Autowired就能正常生效,而让类成为Bean的方式不止@Component一种:
- 用衍生注解:比如你配置了
<context:component-scan base-package="org.controller"/>,这个配置会扫描该包下所有带@Controller、@Component、@Service、@Repository的类并注册为Bean。所以如果你的控制器类加了@Controller,它已经是Spring Bean了,此时在其他Bean中用@Autowired注入这个控制器完全没问题,不需要额外加@Component。 - 用配置类的
@Bean注解:在@Configuration标注的配置类中,通过@Bean方法返回的对象也会被注册为Spring Bean,这类Bean不需要加@Component,同样可以用@Autowired注入。 - 传统XML配置:在XML文件中通过
<bean>标签定义的Bean,也能被@Autowired注入,和@Component无关。
反过来,如果你的类既没通过上述任何方式注册成Spring Bean,那@Autowired肯定无法生效——因为Spring容器里根本找不到这个类的实例,自然没法完成注入。
内容的提问来源于stack exchange,提问作者code
相关产品推荐
相关产品推荐

