spring-boot properties not @Autowired

后端 未结 1 2031
野趣味
野趣味 2020-12-10 18:31

I am trying to get a Spring-boot application going and I am not sure what I am doing wrong here. I have a application.properties file at src/main/resources & src/test/r

相关标签:
1条回答
  • 2020-12-10 18:50

    Your configuration leads to 2 instances of the ConfigurationSettings class and probably one instance overrides the other.

    The 'ConfigurationSettings' has the @Component annotation as you are scanning for components (@ComponentScan) this will lead to an instance. You also have a @Bean annotated method which also leads to an instance. The latter is overridden with the first.

    In short remove the @Component annotation as that isn't needed because you already have a factory method for this class.

    public class ConfigurationSettings { ... }
    

    You should also remove the @PropertySource annotations as Spring-Boot will already load the application.properties for you.

    Finally you should not use the @ContextConfiguration annotation on your test class but the @SpringApplicationConfiguration and pass in your application class (not your configuration class!).

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes=OFAC.class)
    public class OFAConfigurationTest {
    
        @Autowired
        private Environment environment;
    
        @Autowired
        private ConfigurationSettings configurationSettings;
    
        @Test
        public void testConfigurationLoads() {
            assertNotNull(environment);
            assertNotNull(configurationSettings);
        }
    
        @Test
        public void testConfigurationSettingValues() {
            assertEquals("Product Name", configurationSettings.getProduct());
            assertEquals("0.0.1", configurationSettings.getVersion());
            assertEquals("2014 Product", configurationSettings.getCopyright());
        } 
    

    This will fix your runtime configuration problems and will let your test use the power of Spring Boot to configure your application.

    0 讨论(0)
提交回复
热议问题