@Service
//서비스 계층임을 알려주는 어노테이션
public class SlackMessageService {
private final String slackBotToken;
private final String targetChannel;
public SlackMessageService(@Value("${slack.bot-token}") String slackBotToken, @Value("${slack.target-channel}") String targetChannel){
this.slackBotToken = slackBotToken;
this.targetChannel = targetChannel;
}
//@Value 어노테이션으로 application.yml에서 입력해준 bot-token과 target-channel 값 가져옴
public void sendSlackMessage(String message){
Slack slack = Slack.getInstance();
try{
slack.methods().chatPostMessage(
ChatPostMessageRequest.builder()
.token(slackBotToken)
.channel(targetChannel)
.text(message)
.build()
);
System.out.println("메시지 전송 성공");
} catch (IOException | SlackApiException e){
System.out.println("메시지 전송 실패" + e.getMessage());
}
// 예외 처리
}
}
4. SlackMessageApplication에 아래 어노테이션을 추가합니다.
@EnableScheduling
// 스케쥴링 기능을 사용하기 위해 작성해줍니다.
// 이 코드로 인해 코드가 실행이 된다면 자동으로 스케쥴링된 내용이 실행됩니다.
@SpringBootApplication
public class SlackMessageApplication {
public static void main(String[] args) {
SpringApplication.run(SlackMessageApplication.class, args);
}
}