I'm trying to fetch some properties from application.properties
file ad my code is the following:
Main Application class:
package it.mysite;
@SpringBootApplication
@EnableTransactionManagement
public class MailSenderApplication {
public static void main(String[] args){
ConfigurableApplicationContext context = SpringApplication.run(MailSenderApplication.class, args);
System.out.println("*****");
for (String name : context.getBeanDefinitionNames()) {
System.out.println(name);
}
System.out.println("*****");
new MySendService().sendReport();
}
}
My service class:
package it.mysite.service;
@Service
public class MySendService {
@Value("${mail.fc.to}")
private String[] to;
@Value("${mail.fc.subject}")
private String subject;
@Autowired ReportService reportEmailService;
@Autowired MailProperties mailProperties;
public void sendReport(){
if(mailProperties.getTo().length > 0) {
}
}
Class where I fetch the properties:
package it.mysite.properties;
@Component
@ConfigurationProperties("mail.fc")
public class MailProperties {
private String[] to;
public String[] getTo(){
return to;
}
}
Config file:
# Email config
mail.fc.to=my@mail.com
mail.fc.subject=My subject
All of the @Autowired
properties are null
, and also the @Value
properties (I tried to get them in that way also). When I print my context I can see these classes in the bean list, and for what I know my packages hierarchy is correct, so what can be the problem?
EDIT Ok, I got the suggestion from the duplicate question and I changed my main class code as follows: Main Application class:
package it.mysite;
@SpringBootApplication
@EnableTransactionManagement
public class MailSenderApplication {
@Autowired MySendService mySendService;
public static void main(String[] args){
ConfigurableApplicationContext context = SpringApplication.run(MailSenderApplication.class, args);
System.out.println("*****");
for (String name : context.getBeanDefinitionNames()) {
System.out.println(name);
}
System.out.println("*****");
new MailSenderApplication().boot();
}
private void boot(){
mySendService.sendReport();
}
}
But I got the same error. Wasn't that the suggestion?