Malis
Malis

Reputation: 220

Cannot @Autowire configuration

I am absolutely new to TestNG, Spring framework etc. and I'm trying to use the annotation @Value access to configuration file via the @Configuration annotation.

All I'm trying to achieve here is to make the console write out "hi" from the config file accessing the value via @Value. I must be obviously missing the whole point of the @Value annotation (or @Autowired or some other annotations) as all I'm gettting is java.lang.NullPointerException.

I have the following three files (reduced to the absolute minimum):

config.properties

a="hi"

TestConfiguration.java

@Configuration
@PropertySource("config.properties")
public class TestConfiguration {
    @Value("${a}")
    public String A;
}

TrialTest.java

public class TrialTest {
    @Autowired
    private TestConfiguration testConfiguration;

    @Test
    public void test() {
        System.out.println(testConfiguration.A);
   }
}

Thanks a lot.

Upvotes: 0

Views: 530

Answers (2)

George Pantazes
George Pantazes

Reputation: 1130

Make sure that in your config, you are declaring the PropertySourcesPlaceholderConfigurer bean which can resolve the @Value expressions. Declare this bean:

@Configuration
@PropertySource("config.properties")
public class TestConfiguration {
    @Value("${a}")
    public String A;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
    {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

Note that you do not have to do anything with this bean, just by declaring it, it will allow the @Value annotation expressions to work as expected.

You can either redundantly declare this bean in every class that uses a @Value annotation, but that would be bad practice/style as it would keep overwriting the bean in each new declaration. Instead, place this bean at the top most config which imports other configs using @Value and you can recycle the PropertySourcesPlaceholderConfigurer bean from the one place.

Upvotes: 0

jingx
jingx

Reputation: 4024

Try annotate your test class with these:

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes={TestConfiguration.class})

[Edit] sorry I didn't see that OP was using TestNG. The essential point is still that the problem is caused by Spring not being bootstrapped. In TestNG that can be done via extending AbstractTestNGSpringContextTests.

Upvotes: 2

Related Questions