0

I have a @Service class which is called from a web request.

It has a constructor which initializes the list of objects of an implemented type

private List<Interface> interfaceServices;

@Autowired
public ValidateInterfaceService(List<Interface> interfaceServices) {
    this.interfaceServices = interfaceServices;
}

This works as intended except if one of the items in the list has a constructor.

@Service
@Order(3)
public class EvaluateExampleWithConstructor implements Interface {

private LocalDate busDate;

@Autowired
public EvaluateExampleWithConstructor(LocalDate busDate) {
    this.busDate = busDate;
}

If I try and have this class on the list the code cannot run as "no default constructor is found"

If the value passed into the constructor is needed for the method how do I initialize this list correctly?

Hitesh Vaghani
  • 1,342
  • 12
  • 31
Robert Mason
  • 181
  • 3
  • 15
  • 3
    That shouldn't matter. I guess the main issue is that you don't have a bean of type `LocalDate` which would make it that the bean can actually be constructed. – M. Deinum Dec 19 '17 at 12:08
  • A bean where, within the ValidateInterfaceService class? @Autowired LocalDate busdate; ? – Robert Mason Dec 19 '17 at 13:46
  • No in your application context. You have `@Autowired` on your constructor hence it needs a bean of type `LocalDate` to be constructed as a valid bean. – M. Deinum Dec 19 '17 at 13:50
  • Ah, my intention is to not use XML. Is using applicationContext the only way to implement this? – Robert Mason Dec 19 '17 at 14:10
  • What has this to do with XML? You have to have a bean of type `LocalDate`. You can have that in an `@Configuration` class, XML or properties file. – M. Deinum Dec 19 '17 at 14:11
  • And what if the constructor isn't @Autowired? I have managed to get LocalDate within the appcontext xml file, but i am unable to get it working by using a @Configuration class as i'm not sure how to annotate it as a bean – Robert Mason Dec 19 '17 at 14:45
  • What about `@Bean`. – M. Deinum Dec 19 '17 at 14:47
  • @Bean private LocalDate busDate; is not applicable to field – Robert Mason Dec 19 '17 at 15:21

1 Answers1

0

Your problem is caused by the private LocalDate busDate not being a bean in the context. You can create a LocalDate for injection like this:

@Configuration 
public class FooConfiguration {

    @Bean
    public LocalDate busDate() {
        return ...
    }

}

Note this looks rather weird, and you might be better off initializing this date in a different way, depending on your use-case, e.q. using @Value.

tkruse
  • 10,222
  • 7
  • 53
  • 80