Home > OS >  Spring Boot: Why does @Autowired not work for this case?
Spring Boot: Why does @Autowired not work for this case?

Time:05-12

I have a Spring Boot Java application and am trying to inject a @Service into a class. I'm using @Autowired but it's not doing it. I successfully do so in other classes, but not this one.

The service class:

@Service
@Transactional
public class TaskService {
  ...
}

The class where it works is a Vaadin "view" annotated with a Vaadin @Route annotation. I'm assuming there is something going on behind the scenes with the @Route annotation that allows this to work.

@Route("main")
public class TaskListView extends HorizontalLayout {

  private final TaskService taskService;

  public TaskListView(@Autowired TaskService taskService) {
    this.taskService = taskService;
  }

  ...
}

The class where it does not work is also a Vaadin "view", but does not have a @Route annotation, because it is not intended to be navigable to, but rather used as a sub-component of a view (i.e. would be directly instantiated inside a parent view).

public class EditNotesForm extends VerticalLayout {

  @Autowired
  private TaskService         taskService;

  ...
}

The first class uses constructor injection, while the second uses property injection. I can't see why this should make a difference, as I have used both techniques successfully in other applications.

CodePudding user response:

From the Vaadin website:

The only difference between using the router in a standard application and a Spring application is that, in Spring, you can use dependency injection in components annotated with @Route. These components are instantiated by Spring and become Spring-initialized beans. In particular, this means you can autowire other Spring-managed beans.

One way to access Spring components from your regular Vaadin components is by creating static get methods to retrieve your Spring components. Here is one way that can be done... but not the only.

@Component
public class StaticHelper {

    private static StaticHelper instance;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void registerInstance() {
        instance = this;
    }

    public static <T> T getBean(Class<T> class) {
        return instance.applicationContext.getBean(class);
    }

}

So in your example...

private TaskService taskService = StaticHelper.getBean(TaskService.class);

CodePudding user response:

Since EditNotesFormdoesn't have the Route annotation, spring can't autodiscover it and therefore it can't inject any dependency.

Since you want to instantiate it manually, you'll need to provide yourself all dependencies.

But if you still want to benefit from automatic dependency injection, take a look at https://www.baeldung.com/spring-beanfactory

  • Related