SpringBoot is integrated with shiro and the problem that @ Autowired cannot be injected into Service in MyRealm

  • 2021-07-06 11:02:56
  • OfStack

There are many problems on the Internet, such as Spring loading sequence and shiroFilter before Spring automatically assembles bean. In fact, it is possible to ignore the following low-level errors.

In ShiroConfiguration, use @ Bean to inject MyRealm into ApplicationContext, not new objects directly.

Reason and call Service1 in Controller, if it is SpringBean, it cannot be new by itself.

Wrong way:


@Bean(name = "securityManager")
public SecurityManager securityManager() {
    DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
    MyRealm myRealm = new MyRealm();
    manager.setRealm(myRealm);
    return manager;
  }

Correct way:


@Bean(name = "myRealm")
public MyRealm myAuthRealm() {
    MyRealm myRealm = new MyRealm();
    return myRealm;
  }
@Bean(name = "securityManager")
public SecurityManager securityManager(@Qualifier("myRealm")MyRealm myRealm) {
    DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
    manager.setRealm(myRealm);
    return manager;
  }

Summarize


Related articles: