The java implementation injects service or mapper into a normal class

  • 2021-11-01 03:25:08
  • OfStack

Injecting service or mapper into common classes

1. Class with @ Component annotation

2. Inject service to be introduced


  @Autowired
  private UserService userService;

3. Create static files


   private static UserService users;

4. Initialization method


  @PostConstruct
  public void init() {
      users= userService;
  }

5. Call


 users.selectUser(user);

Case where mapper is null

Today, when developing the interface, I was sloppy at 1, which led to a small bug dragging for a long time. Record 1 here

Today, the server hung up and the database could not be linked. You can only write the interface by theory, and then find that the query is empty after the method call, and an exception is thrown. In the Debug environment, after breaking the breakpoint, it is found that step only reaches Xxxmapper. xx (); It stopped. Looking at the mapper object, it is found to be empty.

-Start an investigation:


@SpringBootApplication
@EnableSwagger2
@EnableSwaggerBootstrapUI
@EnableFeignClients(basePackages = {"XXXX.XXXX.api"})
@ComponentScan(value = {"XXXXX.XXXX.api.config", "com.XXXX.gateway.XXX", "com.XXXXX.XXXX.auth"})
@MapperScan("com.XXXX.XXXX.XXX.mapper")
@EnableScheduling
public class IotGateWayParkServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(IotGateWayParkServiceApplication.class);
    }
}

MapperScan can cause this problem. But I do, so rule it out.

--2 check


public class impl{
 @Autowired
 private XxxMapper mapper;
}

@ Autowired also has it, and sometimes idea will be reported red because of this. This can be solved by adding @ Resource, but @ Autowired itself contains @ Resource, so it doesn't matter whether it is added or not. It's for obsessive-compulsive disorder. But I didn't make a mistake here, so I ruled it out.


@Mapper
@Respository
public interfaceXxxMapper{
 
}

I have both @ Mapper and @ Respository. So rule it out.

-What is sloppy:


    @Autowired
    private IotGatewayParkInfoService service;

1 is generally used in controller layer. But I just used new IotGatewayParkInfoService (); So you know what happened


Related articles: