为何@Configuration中new创建的无@Component类的@Autowired能生效
相关代码回顾
@Configuration public class ShiroConfig { @Bean public Realm realm() { return new UserRealm(); } }
// 未添加@Component注解 public class UserRealm extends AuthorizingRealm { @Autowired private UserMapper userMapper; }
问题原因解答
- Spring依赖注入生效的核心前提是目标实例被纳入Spring容器管理,和实例的创建方式、类是否标注
@Component注解没有直接绑定关系:@Component及其派生注解(@Service、@Repository等)只是Spring自动扫描注册Bean的途径之一,通过@Bean注解在配置类中手动注册是另一类常用的Bean注册方式,两种方式注册的Bean都会被Spring完全托管。
- 你在
@Configuration修饰的Shiro配置类中,通过@Bean注解的realm()方法返回了手动new出来的UserRealm实例,这个实例会被Spring识别为容器中的标准Bean:- Spring在初始化该Bean的完整生命周期过程中,会自动扫描类中的
@Autowired、@Resource等依赖注入注解,完成对应依赖的查找和注入,和该类是否添加@Component注解无关。
- Spring在初始化该Bean的完整生命周期过程中,会自动扫描类中的
- 补充误区说明:只有你在脱离Spring上下文的普通业务代码中直接new出来的对象,不会被Spring接管,此时类中的
@Autowired注解才会失效,不会完成注入。
内容的提问来源于stack exchange,提问作者hhyygg2009
相关产品推荐
相关产品推荐

