Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 490
Steve Chambers Avatar asked Oct 27 '15 09:10

Steve Chambers


1 Answers

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.

like image 137
chrylis -cautiouslyoptimistic- Avatar answered Oct 25 '22 12:10

chrylis -cautiouslyoptimistic-