我正在配置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 UserRealm()”创建的,没有@Component。为什么@Autowired能工作?
发布于 2021-08-26 03:59:31
在您的代码中,不需要@Component注释,因为您已经在ShiroConfig类中将UserRealm对象创建为一个spring bean。由于spring是一个spring bean,spring将管理该对象并执行@Autowired注释指定的依赖注入。
如果您没有在ShiroConfig类中将UserRealm对象创建为spring bean,那么您将需要在UserRealm类上使用@Component注释。假设启用了组件扫描,@Component注解将导致spring自动创建UserRealm类的实例作为spring bean。
因此,您要么不使用@Component注释并在配置类中手动创建spring bean,要么使用@Component注释并让spring自动创建spring bean。结果是一样的。
https://stackoverflow.com/questions/68932158
复制相似问题