我正在配置 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
中将 UserRealm
对象创建为 spring bean类(class)。由于它是一个 spring bean,spring 将管理该对象并执行由 @Autowired
注解指定的依赖项注入(inject)。
如果您没有在 ShiroConfig
类中将 UserRealm
对象创建为 spring bean,则需要 @Component
注解在 UserRealm
类上。假设启用了组件扫描,@Component
注释将导致 spring 自动创建 UserRealm
类的实例作为 spring bean。
因此,您要么不使用@Component
注释并在配置类中手动创建spring bean,要么使用@Component
注释并让spring自动创建 Spring Bean 。结果是一样的。
关于spring - 为什么 @Autowired 在 @Configuration 内部时无需 @Component 即可工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68932158/