好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java实现在普通类中注入service或mapper

普通类中注入service或mapper

1、类加@Component注解

2、注入需要引入的service

?

1

2

@Autowired

private UserService userService;

3、建静态文件

?

1

private static UserService users;

4、初始化方法

?

1

2

3

4

@PostConstruct

public void init() {

     users= userService;

}

5、调用

?

1

users.selectUser(user);

mapper为null的情况

今天开发接口的时候,因为一时马虎,导致被一个小bug拖拉了很久,在这里记录一下

今天服务器挂了,数据库链接不了。只能靠着理论写接口,之后发现方法调用后查询为空,并且抛出了异常。在Debug环境下,打了断点后发现step只走到了Xxxmapper.xx();就停止了。查看mapper对象发现为空。

——开始调查:

?

1

2

3

4

5

6

7

8

9

10

11

12

@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可以导致这个问题。但是我有,所以排除。

——二查

?

1

2

3

4

public class impl{

  @Autowired

  private XxxMapper mapper;

}

@Autowired 也有,有时候idea还会因为这个报红,这个可以通过加上@Resource来解决这个强迫症,但是@Autowired里面本身包含@Resource,加不加都无所谓。给强迫症用的。但是这里我没犯错误,所以排除。

?

1

2

3

4

5

@Mapper

@Respository

public interfaceXxxMapper{

 

}

@Mapper 和 @Respository 我都有。所以排除。

——马虎是啥:

?

1

2

@Autowired

private IotGatewayParkInfoService service;

一般在controller层都是这么使用的。但是 我偏偏手贱用了new IotGatewayParkInfoService();所以下场你们也知道了

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/ziyu_nuannuan/article/details/105793056

查看更多关于java实现在普通类中注入service或mapper的详细内容...

  阅读:41次