Steve Chambers Steve Chambers - 5 months ago 44
Java Question

How to override a field value injected by @Value in Spring?

I have a class with a field injected from a property using


public class MyClass {
private String filePath;

My integration tests need to change
to point at some different files.

I tried using reflection to set it before invoking a method:

public class MyClassIT {
@Autowired MyClass myClass;

public void testMyClassWithTestFile1 {
ReflectionTestUtils.setField(myClass, "filePath", "/tests/testfile1.csv");

But when the first method gets invoked, the
injection kicks in and changes the value from what was just set. Could anyone suggest how to resolve this or an alternative approach?

Note: I need Spring to be managing the class (so other dependencies are injected) and other tests are needed for the same class using different test files.


Just use a setter. It's usually preferable to use setter injection instead of field injection anyhow. Even better, convert entirely to constructor and setter injection, and you can usually replace your Spring test context with mocks.