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
You are using two ways to build a Spring's bean. You just need to use one of them.
@Service
over the POJO
@Service
public class SampleService
@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.