We often use the @AutoWired annotation to inject a Service or Mapper interface. It is ok to inject other Service or Mapper interfaces in the Service layer. But if we want to inject a Service or Mapper interface using the @AutoWired annotation in our own encapsulated Utils utility class or in a non-Controller ordinary class, direct injection is not possible because Utils uses static methods and we cannot directly use non-static interfaces. When we meet a problem like this, we have to find a way to solve it.

@Component public class TestUtils { @Autowired private ItemService itemService; @Autowired private ItemMapper itemMapper; public static TestUtils testUtils; @PostConstruct public void init() { testUtils = this; } // use "testutils.xxx" for an example of a method using the service and mapper interfaces in the utils utility class. Method "can the public # # static void test (Item record) {testUtils. ItemMapper. Insert (record); testUtils.itemService.queryAll(); }Copy the code
  1. Add @Component to class DownLoadUtils and declare it a bean Component.
  2. Use @AutoWired to inject the startup class.
  3. Declare a static private variable in DownLoadUtils.
  4. Add a common init method and use the @postConstruct declaration to execute the method at project startup, or at spring container initialization.