当前位置: 首页 > 知识库问答 >
问题:

java.lang.NullPointerException我做错了什么?

公冶元青
2023-03-14

我正在做一个项目,我的意图是运行一个玉米作业,并发送邮件给我的朋友,祝他们生日,我能够从MySQL DB获取电子邮件,并将其与当前日期进行比较,但当涉及到发送电子邮件时,我得到NullPointerException。

我确信应用程序属性没有问题,我在其他项目中也使用了它们,它们的功能正常

//Imports
package dev.teja.happybirthday;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.persistence.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.Email;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;

//Main
@SpringBootApplication
public class HappybirthdayApplication {
    public static void main(String[] args) {
        SpringApplication.run(HappybirthdayApplication.class, args);
    }
    @Autowired
    MyFriendsRepository myFriendsRepository ;
    @Scheduled(cron = "*/30 * * * * *")
    void WishMyFriends() {
        List<MyFriends> myFriendsList = myFriendsRepository.findAll();
        myFriendsList.forEach(friend -> {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
            String CurrentDate= formatter.format(date);
            String GivenDate = formatter.format(friend.dob);
            if (GivenDate.equals(CurrentDate)){
                Job job = new Job();
                Map<String, Object> model = new HashMap<>();
                model.put("Name",friend.name);
                job.sendWish(friend.email,model);
            }
        });
    }
}
@Configuration
@ConditionalOnProperty(name = "scheduling.enabled", matchIfMissing = true)
@EnableScheduling
class Tasks {
}
//Model
@Data
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
class MyFriends {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
    String name;
    @Email
    @Column(unique = true)
    String email;
    @JsonFormat(pattern = "dd/MM/yyyy", shape = JsonFormat.Shape.STRING)
    Date dob;
    Long phoneNumber;
}
//Repository
interface MyFriendsRepository extends JpaRepository<MyFriends, Long> {
}
@RestController
@RequestMapping("/")
class FriendsController {
    @Autowired
    MyFriendsRepository myFriendsRepository;
    @PostMapping("/friends")
    ResponseEntity<MyFriends> createFriend(@RequestBody MyFriends myFriend) {
        myFriendsRepository.save(myFriend);
        return new ResponseEntity<MyFriends>(myFriend, HttpStatus.CREATED);
    }
    @GetMapping("/friends")
    List<MyFriends> getFriends() {
        return myFriendsRepository.findAll();
    }
}
//Interface
interface wisher{
    void sendWish(String email, Map<String, Object> model);
}
//Implementation
@Service
class Job implements wisher{
    @Autowired
    private JavaMailSender sender;
    @Autowired
    private freemarker.template.Configuration config;
    @Override
    public void sendWish(String email,Map<String, Object> model) {
        System.out.println("wishes sent to "+ email);
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                    StandardCharsets.UTF_8.name());
            Template template = config.getTemplate("new-template.ftl");
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            helper.setTo(email);
            helper.setFrom("kondasaitej@gmail.com");
            helper.setSubject("Happy Birthday");
            helper.setText(html,true);
            sender.send(message);
        } catch (MessagingException | IOException | TemplateException e) {
            e.printStackTrace();
        }
    }
}

/**
 * FREEMAKER new-template.ftl
 * <html xmlns="http://www.w3.org/1999/xhtml">
 * <head>
 *     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 *     <title>Comment Alert Mail</title>
 * </head>
 * <body>
 * <p>happy birthday ${Name}</p>
 * </body>
 */

这是我得到以下信息的错误


Hibernate: select myfriends0_.id as id1_0_, myfriends0_.dob as dob2_0_, myfriends0_.email as email3_0_, myfriends0_.name as name4_0_, myfriends0_.phone_number as phone_nu5_0_ from my_friends myfriends0_
wishes sent to kondasaitej@protonmail.com
2020-09-26 21:01:52.012 ERROR 84242 --- [   scheduling-1] o.s.s.s.TaskUtils$LoggingErrorHandler    : Unexpected error occurred in scheduled task

java.lang.NullPointerException: null
    at dev.teja.happybirthday.Job.sendWish(HappybirthdayApplication.java:115) ~[classes/:na]
    at dev.teja.happybirthday.HappybirthdayApplication.lambda$WishMyFriends$0(HappybirthdayApplication.java:53) ~[classes/:na]
    at java.util.ArrayList.forEach(ArrayList.java:1257) ~[na:1.8.0_251]
    at dev.teja.happybirthday.HappybirthdayApplication.WishMyFriends(HappybirthdayApplication.java:44) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_251]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_251]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_251]
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:93) [spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_251]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_251]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_251]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [na:1.8.0_251]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_251]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_251]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_251]

共有1个答案

漆雕宏浚
2023-03-14

尝试在@autowired私有JavaMailSender发送器中添加getting;

 类似资料:
  • 11:15:57创建表如果不存在tblcompany(companyid INT(11)无符号NOT NULL,custfirst VARCHAR(50),custlast VARCHAR(50),company VARCHAR(50),custphone VARCHAR(50), custemail VARCHAR(50),主键(companyid),索引(companyid),约束外键(com

  • 问题内容: 我有一些代码来计算圆的属性: 它计算周长,但不计算其余部分。 问题答案: 是一个,也一个,这意味着不能在第二个打印语句中使用。试试那里。 回想一下,这是浮点数,而整数。在的文档中对此进行了概述(请参阅“ 格式化字符串语法”)。

  • 我正在使用EclipseIDE编程。在完成有关Apache POI的教程后: https://www.youtube.com/watch?v=RsrF2Ku7ad4 我通过eclipse和以下链接创建了一个可执行jar:http://help.eclipse.org/mars/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/tasks-37.htm

  • 我使用的是SPARK-SQL-2.4.1、SPARK-Cassandra-Connector2.11-2.4.1和java8以及apache Cassandra3.0版本。 我有如下所示的spark-submit或spark集群环境,可以加载20亿条记录。 当我检查日志时,我看到警告com.datastax.spark.connector.writer.QueryExecutor-BusyPool

  • 我试图发布一个新的条目到MongoDB,我知道这个问题是我在服务器文件中调用我的路由的地方,但我不知道如何解决这个问题。我需要能够测试在邮递员的API和张贴到数据库。 我得到以下错误: /users/ryan/desktop/leasequery/operations-backend/node_modules/express/lib/router/index.js:458抛出新的TypeError

  • 我正在用spark处理数据,它可以处理一天的数据(40G),但用OOM处理一周的数据失败了: null