Spring Boot Annotation @Autowired of Service fails

前端 未结 1 480
慢半拍i
慢半拍i 2021-02-05 23:47

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. Ho

相关标签:
1条回答
  • 2021-02-06 00:10

    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.

    0 讨论(0)
提交回复
热议问题