Lempkin
Lempkin

Reputation: 1588

Why is my @Autowired null

I got a springboot application (i'm pretty new to it)

Here's my configuration class :

@SpringBootApplication
@EnableScheduling
@Configuration
@ComponentScan(basePackages="com.blah")
public class Application extends SpringBootServletInitializer {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

All my classes are in com.blah.xxx packages. I got another class, in the same package, in which I'm able to use the service by using context, not @Autowired :

@Component
public class MainClass implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        main(args);
    }

    public static void main(String[] args) {
        AbstractApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        ValueService service = (ValueService) context.getBean("valueService");
        System.out.println("blabla" + service.getValues().toString());
        context.close();
    }
}

I got a third class, still in same package and same module, in which I would like to use @Autowired but it's null :

@Component
public class ThirdClass{

@Autowired
private ValueService valueservice;

public ThirdClass() {

    valueservice.getValues(); // <-- Here valueservice is null

}

@Scheduled(cron = "0 0/1 * * * ?")
    public void check() {
        System.out.println("check");
    }

I know that @ComponentScan works well cause in my ValueService (which is in another module, but still package com.blah), I have a ValueDao which is @Autowired and this is working :

@Service("valueService")
public class ValueService {

    @Autowired
    ValueDao valueDao;

What's wrong here and how can I do to use @Autowired in my ThirdClass? Thx!

Upvotes: 0

Views: 179

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

You're trying to access an Autowired field from inside the constructor of the object. That can't possibly work. Spring can't set the value of a field of an object if it doesn't have the object yet. And to have the object, its constructor must first be called. Ergo, at the time the constructor is called, the field is still null.

If you want to use a dependency after the bean is constructed, use a void method annotated with @PostConstruct.

Or do the recommended thing: use constructor injection rather than field injection.

Upvotes: 1

Related Questions