如何只加载一次属性文件?

我正在通过从属性文件获取数据来读取电子邮件消息。我正在使用计时器计划在一段时间后定期读取新消息。我该如何执行此操作?


TimerSchedule.java


public class TimeScheduler

{

    public static void main(String[] args)

    {

        Timer timer = new Timer();

        GmailConfiguration gmailConfiguration = new GmailConfiguration();

        TimerTask timerTask = new TimerTask()

        {

            @Override

            public void run()

            {

                gmailConfiguration.configure();

            }

        };

        timer.scheduleAtFixedRate(timerTask, 500, 30000);

    }

}

我正在从 GmailConfiguration.java 中的属性文件获取数据


这是我的 GmailConfiguration.java


public class GmailConfiguration

{

    private static final Logger LOGGER = LoggerFactory.getLogger(GmailConfiguration.class);


    public void configure()

    {

        JSONParser parser = new JSONParser();

        try

        {

            String propertyFileName = "emailServer.properties";

            InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propertyFileName);


            JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            JSONArray jadata = (JSONArray) jsonObject.get("Servers");

            int len = jadata.size();

            AccessMailMessages readGmail = new AccessMailMessages();

            JSONObject server;

            String name;

            String host;

            String username;

            String password;

            int port;

            String folderName;

            for (int i = 0; i < len; i++)


墨色风雨
浏览 71回答 1
1回答

拉莫斯之舞

Configuration将类与类分开EmailReceiver:// Utilizes "Singleton" patternclass GmailConfiguration {&nbsp; private static final GmailConfiguration INSTANCE = new GmailConfiguration();&nbsp; boolean isConfigured;&nbsp; String host;&nbsp; String port;&nbsp; //etc.&nbsp; public void configure() {&nbsp; &nbsp; if (!isConfigured) {&nbsp; &nbsp; &nbsp; // read in the properties, populate host/port etc.&nbsp; &nbsp; &nbsp; isConfigured = true;&nbsp; &nbsp; }&nbsp; &nbsp; // when called for the second time, reading won't happen&nbsp; }}然后,至于接收电子邮件:class GmailReceiver {&nbsp; public void receive() {&nbsp; &nbsp; AccessMailMessages readGmail = new AccessMailMessages();&nbsp; &nbsp; GmailConfiguration config = GmailConfiguration.INSTANCE;&nbsp; &nbsp; config.configure();&nbsp; &nbsp; readGmail.recieveGmail(config.getName(),&nbsp; &nbsp; &nbsp; &nbsp; config.getHost(),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; config.getPort() /* etc */);&nbsp; }}并确保只安排GmailReceiver
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java