Modularization of Custom Business Objects for Advanced Usage of Spring

  • 2021-07-09 08:01:47
  • OfStack

Several years ago, when using SpringMVC, it was found that springMVC could inject HttpSession and HttpRequest into components:


@Autowired
HttpSession session;

@Autowired
HttpRequest httpRequest;

So I spent 30 minutes tracking the related source code to find out its principle thoroughly, and decided to componentize the users (User/Principle) (although the work was extremely busy at that time, I couldn't help but study it).

The method is as follows:

1. Define the IPrincipal (IUser) interface


interface IPrincipal extends Serializable {
    IPrincipal get()
  }

2. Implement PrincipalObjectFactory


 class PrincipalObjectFactory implements ObjectFactory<IPrincipal>, Serializable {
  @Override
  IPrincipal getObject() {
    def requestAttr = RequestContextHolder.currentRequestAttributes()
    def request = requestAttr.getRequest()
    def p = new PrincipalHelper(request).get()

    new IPrincipal() {
      @Override
      IPrincipal get() {
        p
      }
    }
  }

}

3. Register dependent processors in the context of spring


beanFactory.registerResolvableDependency(IPrincipal, new PrincipalObjectFactory())

With just the above steps, you can use @ Autowired to inject IPrincipal (IUser) into your business code and make it thread safe.

Principle:
Reading the source code of spring will find that if spring finds that there is no implementation class of the interface when injecting the interface, it will look for the relevant dependency resolver from ResolvableDependency.

If the dependency resolver is registered, a proxy class will be injected into the interface. The proxy class's target is ObjectFactory # getObject, where you can implement your IPrincipal (IUser) acquisition.

Summarize

1 Component IPrincipal (IUser) in this way, instead of getting it through tool classes. This method fully embodies the idea of dependency injection of spring, and the system coupling is also reduced a lot.

2 Even if ObjectFactory is injected in the context of spring, spring is not automatically registered and needs to be registered manually.


Related articles: