一次由Spring构造注入引发的错误Parameter 1 of constructor in org.rongyilian.service.impl.VerificationCodeService

SrpringBoot服务启动后报错如下:

Description:

Parameter 1 of constructor in org.rongyilian.service.impl.VerificationCodeServiceImpl required a bean of type 'java.lang.String' that could not be found.


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

Disconnected from the target VM, address: '127.0.0.1:53222', transport: 'socket'

Process finished with exit code 1

以下是本地代码:

@Service
@AllArgsConstructor
public class VerificationCodeServiceImpl implements VerificationCodeService {
    private final RedisService redisService;

    @Value("${redis.key.register}")
    private String REDIS_REGISTER_KEY;
    @Value("${redis.expire.three}")
    private Long THREE_MIN;
    @Override
    public void sendVerificationCode(String phone, String code) {
        String key = REDIS_REGISTER_KEY + ":" + phone;
        redisService.set(key, code, THREE_MIN);
    }
}

报错后我首先想到的是配置文件没注入的问题,检查yml配置文件中是否有语法错误

redis:
  key:
    register: 'user:register'
  expire:
    common: 86400 # 24小时
    three: 180 #3分钟

检查后发现语法正确,百度搜索,说报错信息是由于A类中定义了含参数的构造函数,Spring自动构造和注入时未为该Bean传入参数,引起报错。
反复检查RedisService类发现没有问题

最后发现是由于引用了Lombok的@AllArgsConstructor注解,创造了一个全参的构造器,将@Value修饰的两个变量作为构造器入参,导致报错
以下是修改后的代码,正常启动

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    private final RedisService redisService;

    public VerificationCodeServiceImpl(RedisService redisService) {
        this.redisService = redisService;
    }
    @Value("${redis.key.register}")
    private String REDIS_REGISTER_KEY;
    @Value("${redis.expire.three}")
    private Long THREE_MIN;
    @Override
    public void sendVerificationCode(String phone, String code) {
        String key = REDIS_REGISTER_KEY + ":" + phone;
        redisService.set(key, code, THREE_MIN);
    }
}

版权声明:本文为add_key原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。