[java] Consider defining a bean of type 'service' in your configuration [Spring boot]

I get error when I run the main class.

Error:

Action:
Consider defining a bean of type 'seconds47.service.TopicService' in your configuration.

Description:
Field topicService in seconds47.restAPI.topics required a bean of type 'seconds47.service.TopicService' that could not be found

TopicService interface:

public interface TopicService {

    TopicBean findById(long id);

    TopicBean findByName(String name);

    void saveTopic(TopicBean topicBean);

    void updateTopic(TopicBean topicBean);

    void deleteTopicById(long id);

    List<TopicBean> findAllTopics(); 

    void deleteAllTopics();

    public boolean isTopicExist(TopicBean topicBean);
}

controller:

@RestController
public class topics {

    @Autowired
    private TopicService topicService;

    @RequestMapping(path = "/new_topic2", method = RequestMethod.GET)
    public void new_topic() throws Exception {
        System.out.println("new topic JAVA2");
    }
}

Implementation class:

public class TopicServiceImplementation implements TopicService {

    @Autowired
    private TopicService topicService;

    @Autowired
    private TopicRepository topicRepository;

    @Override
    public TopicBean findById(long id) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public TopicBean findByName(String name) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void saveTopic(TopicBean topicBean) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void updateTopic(TopicBean topicBean) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void deleteTopicById(long id) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<TopicBean> findAllTopics() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void deleteAllTopics() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean isTopicExist(TopicBean topicBean) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

Rest of the classes are defined too. I don't know why its throwing despite declaring componentScan in main class.

Main class:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
@ComponentScan(basePackages = {"seconds47"})
@EnableJpaRepositories("seconds47.repository")
public class Application {

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

I have my packages like this:

seconds47
seconds47.beans
seconds47.config
seconds47.repository
seconds47.restAPI
seconds47.service

This question is related to java spring spring-boot spring-data spring-data-jpa

The answer is


remove annotation configuration like service, repository, components

@Component
@Service

Consider defining a bean of type 'moviecruser.repository.MovieRepository' in your configuration.

This type of issue will generate if you did not add correct dependency. Its the same issue I faced but after I found my JPA dependency is not working correctly, so make sure that first dependency is correct or not.

For example:-

The dependency I used:

    <dependency>
       <groupId>org.springframework.data</groupId>      
       <artifactId>spring-data-jpa</artifactId>
    </dependency>

Description (got this exception):-

Parameter 0 of constructor in moviecruser.serviceImple.MovieServiceImpl required a bean of type 'moviecruser.repository.MovieRepository' that could not be found.

Action:

After change dependency:-

    <!-- 
    <dependency>
       <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

Response:-

2019-09-06 23:08:23.202 INFO 7780 -
[main]moviecruser.MovieCruserApplication]:Started MovieCruserApplication in 10.585 seconds (JVM running for 11.357)


I fixed the problem adding this line @ComponentScan(basePackages = {"com.example.DemoApplication"}) to main class file, just up from the class name

_x000D_
_x000D_
package com.example.demo;_x000D_
_x000D_
import org.springframework.boot.SpringApplication;_x000D_
import org.springframework.boot.autoconfigure.SpringBootApplication;_x000D_
import org.springframework.context.annotation.ComponentScan;_x000D_
_x000D_
@SpringBootApplication_x000D_
@ComponentScan(basePackages = {"com.example.DemoApplication"})_x000D_
public class DemoApplication {_x000D_
_x000D_
 public static void main(String[] args) {_x000D_
  SpringApplication.run(DemoApplication.class, args);_x000D_
 }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_


You are trying to inject a bean in itself. That's obviously not going to work.

TopicServiceImplementation implements TopicService. That class attempts to autowire (by field!) a `TopicService. So you're essentially asking the context to inject itself.

It looks like you've edited the content of the error message: Field topicService in seconds47.restAPI.topics is not a class. Please be careful if you need to hide sensitive information as it makes it much harder for others to help you.

Back on the actual issue, it looks like injecting TopicService in itself is a glitch on your side.


Since TopicService is a Service class, you should annotate it with @Service, so that Spring autowires this bean for you. Like so:

@Service
public class TopicServiceImplementation implements TopicService {
    ...
}

This will solve your problem.


In case you were wondering where to add @Service annotation, then make sure you have added @Service annotation to the class that implements the interface. That would solve this problem.


You have to update your

scanBasePackages = { "com.exm.java" }

to add the path to your service (after annotating it with @service )


I solved this issue by creating a bean for my service in SpringConfig.java file. Please check the below code,

@Configuration 
public class SpringConfig { 

@Bean
public TransactionService transactionService() {
    return new TransactionServiceImpl();
}

}

The path of this file is shown in the below image, Spring boot application folder structure


Even after doing all the method suggested, i was getting the same error. After trying hard, i got to know that hibernate's maven dependency was added in my pom.xml, as i removed it, application started successfully.

I removed this dependency:

<dependency> <groupId>org.hibernate.javax.persistence</groupId>
 <artifactId>hibernate-jpa-2.0-api</artifactId>
             <version>1.0.1.Final</version>
         </dependency>

I resolved by replacing the corrupted jar files.

But to find those corrupted jar files, I have to run my application in three IDE- 1) Intellij Idea 2)NetBeans 3) Eclipse.

Netbeans given me information for maximum number of corrupted jar. In Netbeans along with the run, I use the build option(after right clicking on project) to know more about corrupted jars.

It took me more than 15 hours to find out the root cause for these errors. Hope it help anyone.


@SpringBootApplication @ComponentScan(basePackages = {"io.testapi"})

In the main class below springbootapplication annotation i have written componentscan and it worked for me.


Please make sure that you have added the dependency in pom.xml or gradle file

spring-boot-starter-data-jpa


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to spring-boot

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Why am I getting Unknown error in line 1 of pom.xml? Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured How to resolve Unable to load authentication plugin 'caching_sha2_password' issue ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName ERROR Source option 1.5 is no longer supported. Use 1.6 or later How to start up spring-boot application via command line? JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Examples related to spring-data

Call another rest api from my server in Spring-Boot Consider defining a bean of type 'service' in your configuration [Spring boot] How to beautifully update a JPA entity in Spring Data? Unable to find a @SpringBootConfiguration when doing a JpaTest Spring Data and Native Query with pagination Spring Boot - Loading Initial Data Disable all Database related auto configuration in Spring Boot crudrepository findBy method signature with multiple in operators? What is this spring.jpa.open-in-view=true property in Spring Boot? Spring Data JPA and Exists query

Examples related to spring-data-jpa

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? No converter found capable of converting from type to type Consider defining a bean of type 'service' in your configuration [Spring boot] Check date between two other dates spring data jpa How to beautifully update a JPA entity in Spring Data? Spring Data and Native Query with pagination Disable all Database related auto configuration in Spring Boot crudrepository findBy method signature with multiple in operators? How does the FetchMode work in Spring Data JPA