ChatGPT解决这个技术问题 Extra ChatGPT

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

I am trying to write a SOAP service using Spring, however I receive a Dependency Injection issue. I'm having problems using @Autowired through the Service like this:

    public interface UserDao {
    User getUser(String username);
}

Implementation for Dao as below:

  @Controller("userDao")
    public class UserDaoImpl implements UserDao {
    private static Log log = LogFactory.getLog(UserDaoImpl.class);

    @Autowired
    @Qualifier("sessionFactory")
    private LocalSessionFactoryBean sessionFactory;

    @Override
    public User getUser(String username) {
        Session session = sessionFactory.getObject().openSession();
        // Criteria query = session.createCriteria(Student.class);
        Query query = session
                .createQuery("from User where username = :username");
        query.setParameter("username", username);
        try {
            System.out.println("\n Load Student by ID query is running...");
            /*
             * query.add(Restrictions.like("id", "%" + id + "%",
             * MatchMode.ANYWHERE)); return (Student) query.list();
             */
            return (User) query.uniqueResult();
        } catch (Exception e) {
            // TODO: handle exception
            log.info(e.toString());
        } finally {
            session.close();
        }
        return null;
    }

}

and

public interface UserBo {
    User loadUser(String username);
}

and

public class UserBoImpl implements UserBo {
    @Autowired
    private UserDao userDao;

    @Override
    public User loadUser(String username) {
        // TODO Auto-generated method stub
        return userDao.getUser(username);
    }

}


@WebService
@Component
public class UserService {

    @Autowired
    private UserBo userBo;

    @WebMethod(operationName = "say")
    public String sayHello(String name) {
        return ("Hello Java to " + name);
    }

    @WebMethod(operationName = "getUser")
    public User getUser(String username) {
        return userBo.loadUser(username);
    }
}

The below is xml mapping file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ws="http://jax-ws.dev.java.net/spring/core"
    xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://jax-ws.dev.java.net/spring/core
    http://jax-ws.java.net/spring/core.xsd
    http://jax-ws.dev.java.net/spring/servlet
    http://jax-ws.java.net/spring/servlet.xsd

    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <context:annotation-config />

    <context:component-scan base-package="edu.java.spring.ws"></context:component-scan>
    <context:component-scan base-package="edu.java.spring.ws.dao"></context:component-scan>
    <bean id="userDao" class="edu.java.spring.ws.dao.UserDaoImpl"></bean>
    <!-- <context:component-scan base-package="edu.java.spring.ws.bo"></context:component-scan>
     -->
    <wss:binding url="/user">
        <wss:service>
            <ws:service bean="#userService" />
        </wss:service>
    </wss:binding>
    <bean id="userBo" class="edu.java.spring.ws.bo.impl.UserBoImpl"></bean>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/contentdb" />
        <property name="username" value="root" />
        <property name="password" value="123456" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan" value="edu.java.spring.ws.model" />
    </bean>
</beans>

And the error thrown when deploying is: Here is the updated stack trace:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.sun.xml.ws.transport.http.servlet.SpringBinding#0' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot create inner bean '(inner bean)#538071ba' of type [org.jvnet.jax_ws_commons.spring.SpringService] while setting bean property 'service'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#538071ba' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'userService' while setting bean property 'bean'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.bo.UserBo edu.java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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)}
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:290)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4992)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5490)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#538071ba' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Cannot resolve reference to bean 'userService' while setting bean property 'bean'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.bo.UserBo edu.java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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)}
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:336)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1456)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:276)
    ... 24 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.bo.UserBo edu.java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328)
    ... 30 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.bo.UserBo edu.java.spring.ws.UserService.userBo; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 38 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userBo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 40 more
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private edu.java.spring.ws.dao.UserDao edu.java.spring.ws.bo.impl.UserBoImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 51 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [edu.java.spring.ws.dao.UserDao] 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)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 53 more
Can you add the implementation of your UserDao class? Is that annotated as Reporitory?
Sorry, I missed to attach implementation for Dao . I updated as above.
Please add Repository annotation as requested by @Jens. Also make an entry in the mapping file.
+nILESH:I added implementation method. Please check again.
Sorry piggybacking off this google result to say: if you're having trouble figuring out where the problem is after you've refactored some stuff around, check to make sure that you haven't maybe moved a method that called a service... into that same service. Then if you're tired enough maybe you made the mistake of trying to autowire that service into itself.

d
diegomtassis

Look at the exception:

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency

This means that there's no bean available to fulfill that dependency. Yes, you have an implementation of the interface, but you haven't created a bean for that implementation. You have two options:

Annotate UserDaoImpl with @Component or @Repository, and let the component scan do the work for you, exactly as you have done with UserService.

Add the bean manually to your xml file, the same you have done with UserBoImpl.

Remember that if you create the bean explicitly you need to put the definition before the component scan. In this case the order is important.


I really created a bean in xml file. Please check again to help me.Thanks
If you add the definition of the bean explicitly in the xml file then it has to be placed before the component scan that creates the dependent bean. I will improve the answer.
Y
Yasin Okumuş

Add the annotation @Repository to the implementation of UserDaoImpl

@Repository
public class UserDaoImpl implements UserDao {
    private static Log log = LogFactory.getLog(UserDaoImpl.class);

    @Autowired
    @Qualifier("sessionFactory")
    private LocalSessionFactoryBean sessionFactory;

    //...

}

I tried as your suggestion but it's not good.The trace log as below Error creating bean with name 'userDaoImpl': Injection of autowired dependencies failed; nested exception isorg.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.orm.hibernate4.LocalSessionFactoryBean edu.java.spring.ws.dao.impl.UserDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [edu.java.spring.ws.dao.UserDaoImpl] for bean with name 'userDao'
@user2659694 look here maybe this helps.
W
WesternGun

In my case, the application context is not loaded because I add @DataJpaTest annotation. When I change it to @SpringBootTest it works.

@DataJpaTest only loads the JPA part of a Spring Boot application. In the JavaDoc:

Annotation that can be used in combination with @RunWith(SpringRunner.class) for a typical JPA test. Can be used when a test focuses only on JPA components. Using this annotation will disable full auto-configuration and instead apply only configuration relevant to JPA tests. By default, tests annotated with @DataJpaTest will use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource). The @AutoConfigureTestDatabase annotation can be used to override these settings. If you are looking to load your full application configuration, but use an embedded database, you should consider @SpringBootTest combined with @AutoConfigureTestDatabase rather than this annotation.


j
julianm

I just solved this error happening in my tests.

Just make sure your test class has all dependencies in the attributes of the class being tested annotated with @MockBean so SpringBoot test context can wire your classes correctly.

Only if you are testing controller: you need also class annotations to load the Controller context propertly.

Check it out:

@DisplayName("UserController Adapter Test")
@WebMvcTest(UserController.class)
@AutoConfigureMockMvc(addFilters = false)
@Import(TestConfig.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper objectMapper;

@MockBean
private CreateUserCommand createUserCommand;

@MockBean
private GetUserListQuery getUserListQuery;

@MockBean
private GetUserQuery getUserQuery;

Stumbled upon you answer after spending good 7 hours ! Thanks.
G
Georgi Georgiev

I added @Service before impl class and the error is gone.

@Service
public class FCSPAnalysisImpl implements FCSPAnalysis
{}

S
SkyWalker

You seems to be missing implementation for interface UserDao. If you look at the exception closely it says

No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency:

The way @Autowired works is that it would automatically look for implementation of a dependency you inject via an interface. In this case since there is no valid implementation of interface UserDao you get the error.Ensure you have a valid implementation for this class and your error should go.

Hope that helps.


J
Jitendra Nandre

We face this issue but had different reason, here is the reason:

In our project found multiple bean entry with same bean name. 1 in applicationcontext.xml & 1 in dispatcherServlet.xml

Example:

<bean name="dataService" class="com.app.DataServiceImpl">
<bean name="dataService" class="com.app.DataServiceController">

& we are trying to autowired by dataService name.

Solution: we changed the bean name & its solved.


B
Buhake Sindi

In my case I had to move the @Service annotation from the interface to the implementation class.


Please explain a bit.
Adding @Service onto my class solved it, my class is now automatically picked up by the spring injection framework. But, I don't understand why :( p.s. Adding atComponent works too! It's a lower-level class so I'd use that instead.
K
Kumar Gaurav Sharma

Add repository annotation before your DAO Implementation Class. example:

@Repository
public class EmpDAOImpl extends BaseNamedParameterJdbcDaoSupportUAM 
implements EmpDAO{ 
}

i
invzbl3

I've encountered similar issue in multi-module project w/ expected at least 1 bean which qualifies as autowire candidate like:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.stockclient.repository.StockPriceRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

And in my use case the cause of issue was missing annotation @EnableJpaRepositories, which is used for enabling auto configuration support for Spring Data JPA required to know the path of JPA repositories.

By default, it will scan only the main application package and its sub packages for detecting the JPA repositories.

For more details you can refer, for instance, to this article.


k
kris

Could me multiple reason for this. But you want might forget to add as @Bean for component which you have did @Autowired.

In my case, i have forgot to decorate with @Bean which causing this issue.


M
Marcin T.P. Łuczyński

In my case, I had the following structure of a project:

https://i.stack.imgur.com/0Pmyd.png

When I was running the test, I kept receiving problems with auro-wiring both facade and kafka attributes - error came back with information about missing instances, even though the test and the API classes reside in the very same package. Apparently those were not scanned.

What actually helped was adding @Import annotation bringing the missing classes to Spring classpath and making them being instantiated.


J
Jack

When you use @DataJpaTest you need to load classes using @Import explicitly. It wouldn't load you for auto.


n
nikhil2000

for me, the culprit was the size of dependencies.

some of the project related dependencies were not downloaded properly, and it caused this error. checked with a teammate with similar setup and added the jars again.


A
Ash

In my case, I solved it by importing all the autowired dependencies (with @Autowired annotation) from the controller class with @MockBean annotator in the test class. Ex.:

Controller.java

@Autowired
private Service service

@Autowired
private Dao daoService

ControllerTest.java

@MockBean
private Service service

@MockBean
private Dao daoService

Keep in mind that this is only needed if you have tests focusing on classes rather than the entire app. Another approach to avoid this error is by loading the entire app at once with @SprintTest instead of @WebMvcTest(Controller.class). This guide has some more info on testing basics that could help.


H
Hakan Fıstık

I missed to add

@Controller("userBo") into UserBoImpl class.

The solution for this is adding this controller into Impl class.


I disaggree with that answer! Please revisit and see what all things you added.
Please wait for me check again.
Your BO isn't a Controller!
Don't mark an answer as "accepted" just because it's yours. Find the best answer and accept it.

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now