Home > Enterprise >  Is this the best practice for SimpleDateFormat in spring boot?
Is this the best practice for SimpleDateFormat in spring boot?

Time:04-24

The SimpleDateFormat is not a thread-safe class.

Is this the best practice to write a Utility Service for SimpleDateFormat in spring boot?

@Service
public class DateConvertUtil {

    private SimpleDateFormat getDateFormateInstance() {
        return new SimpleDateFormat("yyyy/MM/dd");
    }

    public String parseDateToString(Date date) {
        SimpleDateFormat sdf = getDateFormateInstance();
        return sdf.format(date);
    }

    public Date parseStringToDate(String date) throws ParseException {
        SimpleDateFormat sdf = getDateFormateInstance();
        return sdf.parse(date);
    }

}

CodePudding user response:

Base on my opinion :

  • Annotation like @Service have the default scope is singleton.
  • You do not contain any mutable state in the @Service, the problem of the thread-safe belong to the mutable state, which can be accessed between multiple thread and will make the system confused.
  • Bonus : You can use @Configuration and @Bean for create bean for this Utils class.

So I think it does not harm the system as well. Just try it and find the problem. Best practices require lots of practices

CodePudding user response:

It looks like that you have a faulty structure in your project . Create a package Utill and put there all your classes or methods which you want to share in your project

  • Related