Search code examples
javaspringautowiredspring-ioc

Wiring a bean and a value in a constructor


I'm using Spring. I have this class:

@Service
public class FooService {

    @Value("${xml.file.path}")
    String xmlFilePath;

    @Autowired
    ResourceLoader ctx;
}

I really hate wiring properties and would prefer to use a constructor but anything I come up is getting a weird "constructor FooService in class FooService cannot be applied to given types". Is it possible to use construction wiring in this case?


Solution

  • This should work:

    @Service
    public class FooService {
        private String xmlFilePath;
        private ResourceLoader ctx;
    
        @Autowired
        public FooService(@Value("${xml.file.path}") String xmlFilePath, ResourceLoader ctx) {
            super();
            this.xmlFilePath = xmlFilePath;
            this.ctx = ctx;
        }
    }