Java抽象类使用@Autowired注入实例

示例代码如下:
抽象类

1
2
3
4
5
6
7
8
9
10
public abstract class AbstractWaterMark {

@Autowired
private AchievementApplicationService achievementApplicationService;

public AchievementApplication queryByCode(String code){
return achievementApplicationService.queryByCode(code);
}

}

增加子类(需要@Service注解)

1
2
3
4
@Service
public class WaterMark extends AbstractWaterMark {

}

测试类(装配抽象类/子类)

1
2
3
4
5
6
7
8
@Autowired
private WaterMark waterMark;

@PostMapping("/test")
public SingleResult test() {
AchievementApplication achievementApplication = waterMark.queryByCode("ZGGX-ZF-YN-20220004");
return new SingleResult(achievementApplication);
}

注意事项:

  • 装配抽象类也可以

    1
    2
    @Autowired
    private AbstractWaterMark abstractWaterMark;
  • 使用new WaterMark();的方式,依然会出现空指针异常

  • 必须有子类,且子类使用@service注解修饰

参考链接