-1

I have a bean used in MyApp, but when I have MyApp app = new MyApp(), then carIF is null. What is the best practice to solve this issue? I have tried to make MyApp as a bean as well by adding @Component, so I don't need to do 'new MyApp()', but it turns out I need to keep making a java class as bean in my java classes calling workflow, which I don't think it is a right approach. How to solve the issue like this?

public class MyApp() {
@Autowired
private CarIF carIF; 
FullStackDeveloper
  • 910
  • 1
  • 16
  • 40

1 Answers1

1

When you instantiate the class on your own (MyApp()) you are not taking advantage of Spring-managed Beans and Spring Dependency Injection features. When you do it like that you can't expect Spring to inject a CarIF instance in your newly created MyApp instance.

As you mentioned, you should make MyApp a Spring-managed Bean by, for example, annotate it with @Component as follows:

@Component
public class MyApp() {
   @Autowired
   private CarIF carIF;
}

This will generally work, but it really depends on your project setup and if you are following a usual Spring project structure.

João Dias
  • 16,277
  • 6
  • 33
  • 45
  • Thanks. I can make MyApp as bean like you mentioned, but then I also need to make the class which call MyApp as bean, this will be a sequence change, for my project, this sounds not scalable. – FullStackDeveloper Sep 29 '21 at 00:56
  • Well but you either use Spring or you don't. If you don't want to add the annotations needed or the configurations that Spring requires then just drop Spring. – João Dias Sep 29 '21 at 08:08