变量sendMessageService未在默认构造函数中初始化

问题描述 投票:0回答:1

我正在尝试通过 Spring Boot 实现电报机器人 描述了一些简单的组件,但在启动项目时遇到问题:“错误:变量 sendMessageService 未在默认构造函数中初始化” 我的组件:

@Component
@RequiredArgsConstructor
public class MessageHandler {

    private final SendMessageService sendMessageService;

    public void sendMessage(NotificationDto notification) throws TelegramApiException {
        sendMessageService.sendMessage(getMessage(notification));
    }

    private String getMessage(NotificationDto notificationDto) {
        return notificationDto.getMessage();
    }
}
@Service
@RequiredArgsConstructor
public class SendMessageService {

    .....

    public void sendMessage(String message) throws TelegramApiException {
        for (Long chatId : CHAT_IDS) {
            SendMessage sendMessage = generateMessage(chatId, message);
            telegramBotService.execute(sendMessage);
        }
    }

构建.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.1.8'
    id 'io.spring.dependency-management' version '1.1.4'
}

group = 'by.teashop.tg'
version = '0.0.1-SNAPSHOT'

java {
    sourceCompatibility = '17'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.telegram:telegrambots:6.0.1'
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.8'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    implementation 'io.github.openfeign:feign-slf4j:11.9.1'
    implementation 'io.github.openfeign:feign-jackson:11.9.1'
    implementation 'io.github.openfeign:feign-httpclient:11.9.1'

    implementation 'org.projectlombok:lombok'
}

tasks.named('bootBuildImage') {
    builder = 'paketobuildpacks/builder-jammy-base:latest'
}

tasks.named('test') {
    useJUnitPlatform()
}

使用@depensOn注释尝试了很多不同的选项,添加@ComponentScan等..

spring-boot telegram-bot
1个回答
1
投票

已经有了

@RequiredArgsConstructor
,所以不需要
@Autowired
- Spring Boot 将自动装配唯一提供的构造函数。

我猜测这是因为您在依赖项中缺少 lombok 的

annotationProcessor
,因此它不会创建构造函数。您的
dependencies
应如下所示:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.telegram:telegrambots:6.0.1'
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.8'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    implementation 'io.github.openfeign:feign-slf4j:11.9.1'
    implementation 'io.github.openfeign:feign-jackson:11.9.1'
    implementation 'io.github.openfeign:feign-httpclient:11.9.1'

    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
}

考虑使用

https://start.spring.io/
以避免将来出现此类问题

© www.soinside.com 2019 - 2024. All rights reserved.