【问题标题】:why @Autowired work without @Component when inside @Configuration为什么@Autowired 在@Configuration 内部没有@Component 工作
【发布时间】:2021-10-26 03:20:14
【问题描述】:

我正在配置 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 工作?

【问题讨论】:

    标签: spring spring-mvc shiro


    【解决方案1】:

    在您的代码中,@Component 注释不是必需的,因为您已在 ShiroConfig 类中将 UserRealm 对象创建为 spring bean。因为它是一个spring bean,所以spring会管理对象并执行@Autowired注解指定的依赖注入。

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

    所以你要么不使用@Component注解并在你的配置类中手动创建spring bean,要么使用@Component注解让spring自动创建spring bean。结果是一样的。

    【讨论】:

    • 最后,我找到了一种更好的方法,使用构造函数在 UserRealm 中注入 UserMapper,并通过 Bean 领域中的字段注入 UserMapper。谢谢!
    猜你喜欢
    • 2021-01-27
    • 2015-09-14
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多