Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Annotation @Autowired of Service fails

I'm trying to use @Autowired annotation for a Service class in Spring Boot application, but it keeps throwing No qualifying bean of type exception. However, if I change the service class to a bean, then it works fine. This is my code:

package com.mypkg.domain;
@Service
public class GlobalPropertiesLoader {

    @Autowired
    private SampleService sampleService;        
}

package com.mypkg.service;
@Service
public class SampleService{

}

And this is my SpringBoot class:

package com.mypkg;

import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

@SpringBootApplication
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableTransactionManagement
public class TrackingService {
    private static final Logger LOGGER = LoggerFactory.getLogger(TrackingService.class);

    static AnnotationConfigApplicationContext context;

    public static void main(String[] args) throws Exception {
        SpringApplication.run(TrackingService.class, args);
        context = new AnnotationConfigApplicationContext();
        context.refresh();
        context.close();

    }

}

When I try to run this, I get the following exception:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mypkg.service.SampleService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

But when I remove the @Service annotation from the SampleService class, and add it as a bean in my AppConfig class as below, it works fine:

@Configuration
public class AppServiceConfig {

    public AppServiceConfig() {
    }

    @Bean(name="sampleService")
    public SampleService sampleService(){
        return new SampleService();
    }

}

The classes are in different packages. I am not using @ComponentScan. Instead, I'm using @SpringBootApplication which does that automatically. However, I tried with ComponentScan as well but that didn't help.

What am I doing wrong here?

like image 669
drunkenfist Avatar asked Apr 22 '15 20:04

drunkenfist


People also ask

Why is @autowired not working?

When @Autowired doesn't work. There are several reasons @Autowired might not work. When a new instance is created not by Spring but by for example manually calling a constructor, the instance of the class will not be registered in the Spring context and thus not available for dependency injection.

What is the actual use of @autowired @qualifier @component annotation?

There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property. In such cases, you can use the @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired.

What does @autowired do in Spring boot?

Starting with Spring 2.5, the framework introduced annotations-driven Dependency Injection. The main annotation of this feature is @Autowired. It allows Spring to resolve and inject collaborating beans into our bean.

What is true @autowired annotation?

The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. The @Autowired annotation can be used to autowire bean on the setter method just like @Required annotation, constructor, a property or methods with arbitrary names and/or multiple arguments.


1 Answers

You are using two ways to build a Spring's bean. You just need to use one of them.

  1. @Service over the POJO

     @Service
     public class SampleService
    
  2. @Bean in the configuration class which must be annotated with @Configuration

     @Bean
     public SampleService sampleService(){
         return new SampleService();
     }
    

@Autowired is resolved by class type then @Bean(name="sampleService") is not needed is you have only one bean with that class type.

EDIT 01

package com.example

@SpringBootApplication
public class Application implements CommandLineRunner {

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

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Override
    public void run(String... strings) throws Exception {
        System.out.println("repo " + userRepository);
        System.out.println("serv " + userService);
    }
}

package com.example.config

@Configuration
public class AppConfig {

    @Bean
    public UserRepository userRepository() {
        System.out.println("repo from bean");
        return new UserRepository();
    }

    @Bean
    public UserService userService() {
        System.out.println("ser from bean");
        return new UserService();
    }
}

package com.example.repository

@Service
public class UserRepository {

    @PostConstruct
    public void init() {
        System.out.println("repo from @service");
    }
}

package com.example.service

@Service
public class UserService {

    @PostConstruct
    public void init() {
        System.out.println("service from @service");
    }

}

Using this code you can comment the AppConfig class and then you will see how UserRepository and UserService are autowired. After that comment @Service in each class and un-comment AppConfig and classes will be autowired too.

like image 118
Eddú Meléndez Avatar answered Sep 23 '22 11:09

Eddú Meléndez