0

Is is possible to add a non-empty default constructor to a FactoryBean, where the parameter is injected by @Value?

@Service
public class DateTimeFormatterFactory implements FactoryBean<DateTimeFormatter> {
    private DateTimeFormatter formatter;

    @Autowired
    public DateTimeFormatterFactory(@Value("${custom.format}") String format) {
        formatter = DateTimeFormatter.ofPattern(format);
    }

    @Override
    public DateTimeFormatter getObject() {
        return formatter;
    }

    @Override
    public Class<?> getObjectType() {
        return DateTimeFormatter.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

/edit: I should have added the error message. Spring complains that there is not "default" constructor without arguments. But if I add one, then my @Value constructor is never called...

membersound
  • 81,582
  • 193
  • 585
  • 1,120

1 Answers1

1

Yes, but you don't need a constructor parameter for this.

Instead, you can create a PostConstruct method and initialize the formatter therein.

For example,

@Value("${custom.format}")
private String desiredDateFormat;

@PostConstruct
public void postConstruct()
{
    formatter = DateTimeFormatter.ofPattern(desiredDateFormat);
}

Option 2 (A.K.A response to comment)

If you only need the value to create the DateTimeFormatter, then just use it to create the DateTimeFormatter in a "setter-like" method that I will call a "settee" (because I don't know what to actually call it). Here is some code:

@Value("${custom.format}")
public void createDateTimeFormatter(
    final String desiredDateFormat)
{
    formatter = DateTimeFormatter.ofPattern(desiredDateFormat);
}
DwB
  • 37,124
  • 11
  • 56
  • 82
  • The drawback is that I'd have to introduce an extra variable for the `@Value` injection that is afterwards never used again. I tend to avoid variables that are only used once... – membersound May 01 '18 at 07:13
  • Option 2 is derived from the @Bartosz Bilicki answer to this question: https://stackoverflow.com/questions/33562731/spring-autowire-property-vs-setter – DwB May 01 '18 at 13:19
  • Having the `@Value` on top of the setter (instead on the parameter) worked. That's what I was looking for! – membersound May 02 '18 at 11:12