Steve Chambers Steve Chambers - 1 month ago 13
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

@Value
:

public class MyClass {
@Value(${property.key})
private String filePath;
...


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

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

public class MyClassIT {
@Autowired MyClass myClass;

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


But when the first method gets invoked, the
@Value
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.

Answer

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.

Comments