I am configuring the 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 was create using "new UserRealm()",without @Component. why the @Autowired work?
CodePudding user response:
In your code, the @Component
annotation is not required because you've created the UserRealm
object as a spring bean in the ShiroConfig
class. Since it's a spring bean, spring will manage the object and perform the dependency injections specified by the @Autowired
annotation.
If you didn't create the UserRealm
object as a spring bean in the ShiroConfig
class, you would then need the @Component
annotation on the UserRealm
class. The @Component
annotation would cause spring to automatically create an instance of the UserRealm
class as a spring bean, assuming component scanning is enabled.
So you either don't use a @Component
annotation and manually create spring beans in your configuration class, or use the @Component
annotation and let spring automatically create the spring bean. The result is the same.