简体   繁体   中英

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?

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM