Java.lang.NullPointerException solve the problem of non-controller using annotation injection being given @Autowired

        In SpringMVC framework, we often want to use @Autowired comment or injecting Service Mapper interface, we also know that the injection service interface controller layer, into other service mapper interface or interfaces are possible in the service layer, but if we to Utils tools of our own package, or non-controller used in the general category @Autowired annotation or injecting Service Mapper interfaces, direct injection is not possible, because Utils use a static method, we can not use non-static interface directly when we encounter such a problem, we have to find a way to solve.

        There are two ways to solve this problem, the first comment is the way, the second is xml configuration, we use the following annotation in @Autowired utils methods:

@Component 
 public  class TestUtils { 
    @Autowired 
    Private ItemService ItemService; 
     
    @Autowired 
    Private ItemMapper itemMapper; 
     
    public  static TestUtils testUtils; 
     
    @PostConstruct // for the dependency injection method after completion of execution need to perform any initialization 
    public  void the init () {     
        testUtils = the this ; 
    } 
     
    // utils tools used in examples and methods mapper service interface, with ". testUtils.xxx method" can be a       
    public  static  void Test (Item Record) { 
        testUtils.itemMapper.insert (Record); 
        testUtils.itemService.queryAll (); 
    } 
}

The second method is the way xml configuration is very simple, we can @PostConstruct the init () method to remove the annotations, configure the following bean in spring-comtext.xml the like, which do not have what to write, Is not it simple?

<the bean ID = "testUtils" class = "written here utils package full path name of the class" init-method = "init" > </ bean>

 

Guess you like

Origin www.cnblogs.com/dukedu/p/11801561.html