user1578872
user1578872

Reputation: 9028

Spring boot property autowiring not working

I have a Spring boot 2.3.3.RELEASE project.

Main Application class,

    @SpringBootApplication()
    public class TestApplication {
           ...
    }
    
    @ConfigurationProperties(prefix = "test")
    public class TestProperties {
      ...
    }
    
    @Configuration
    @EnableConfigurationProperties({TestProperties.class})
    public class TestConfiguration {
    
    }

@Service
public class AmazonEmailService {

    private final AmazonSimpleEmailService client;
    
    @Autowired
    private TestProperties props;

    public AmazonEmailService() {
      props.getEmail(); // Here props is null ...
    }

}

Here, TestProperties autowiring is null in AmazonEmailService. Not sure what is missing.

Other Autowiring works in other classes.

Upvotes: 0

Views: 132

Answers (2)

Chayne P. S.
Chayne P. S.

Reputation: 1638

Can you use @Autowired on the constructor instead?

private TestProperies props;    

@Autowired
public AmazonEmailService(TestProperties props){
   this.props=props; 
   props.getEmail(); //Ok now.
}

This is because using @Autowired on property, Spring inject the value AFTER object create. But in your case, you try to use the props inside the contructor. At that moment, it's still null

Upvotes: 3

Aswin
Aswin

Reputation: 56

Add @Component annotation on TestProperties class

Upvotes: 0

Related Questions