0

I've been trying to make spring scan for beans and components inside the startup class itself to no avail. Here's my startup class:

@SpringBootApplication
@EnableAsync
@Configuration
@EnableAutoConfiguration
public class CastleApplication{

    @Autowired
    BalanceInfoDAO balanceInfoDAO;

    public static void main(String[] args) {
        SpringApplication.run(CastleDaoApplication.class, args);
        new CastleApplication().printBalance("XXXXXXXX");
    }

    void printBalance(String number) {
        float monthlyAmount = this.balanceInfoDAO.getMonthlyAmount(msisdn);
        System.out.println(monthlyAmount);
    }
}

When I run the application, the ivar balanceInfoDAO is null. There is a class implementing the BalanceInfoDao interface which is annotated with @Service and it's under the same base package as startup class. So what do I have to do to make spring inject the dependency inside the startup class itself?

Mikayil Abdullayev
  • 12,117
  • 26
  • 122
  • 206
  • 1
    You are creating a new instance yourself, get the instance from the context instead of creating a new instance. – M. Deinum Dec 11 '17 at 12:54
  • 1
    @M.Deinum, I've seen the answer you've suggested but I go annotations way rather than xml based configuration, so couldn't quite get it. Could you please elaborate on this? – Mikayil Abdullayev Dec 11 '17 at 13:00
  • If you want start the Spring Boot application by passing to it an argument (or not) and invoke a instance method of it as the application is loaded, this could maybe help you : https://stackoverflow.com/questions/46617044/how-to-use-autowired-autowired-references-from-mainstring-args-method/46617190#46617190 – davidxxx Dec 11 '17 at 13:03
  • It doesn't matter if you use XML or not. Creating a new instance yourself will never be injected. Get the one from the context instead of creating a new instance. – M. Deinum Dec 11 '17 at 13:04
  • OK, @M.Deinum, if you tell me how to get the application context, then I think I'll be able to do the rest. – Mikayil Abdullayev Dec 11 '17 at 13:12

0 Answers0