为什么@Autowired 在@Configuration 中没有@Component 的情况下工作

why @Autowired work without @Component when inside @Configuration

我正在配置 shiro-spring-starter。

@Configuration
public class ShiroConfig {
    @Bean
    public Realm realm() {
        return new UserRealm();
    }
}
\Without @Component
public class UserRealm extends AuthorizingRealm {
    
    @Autowired
    private UserMapper userMapper;
}

UserRealm 是使用“new UserRealm()”创建的,没有@Component。 为什么 @Autowired 起作用?

在您的代码中,不需要 @Component 注释,因为您已经在 ShiroConfig [=28= 中将 UserRealm 对象创建为 spring bean ].由于它是一个 spring bean,spring 将管理对象并执行由 @Autowired 注释指定的依赖项注入。

如果您没有在 ShiroConfig class 中将 UserRealm 对象创建为 spring bean,那么您将需要 @Component 注释在 UserRealm class 上。 @Component 注释会导致 spring 自动创建 UserRealm class 的实例作为 spring bean,假设启用了组件扫描。

因此,您要么不使用 @Component 注释并在配置 class 中手动创建 spring beans,要么使用 @Component 注释并让 spring 自动创建 spring bean。结果是一样的