Java 没有定义命名的 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40035723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:39:22  来源:igfitidea点击:

No bean named is defined

javaspringjunit

提问by Dolphin

I am using JUnit to test Component of Spring,throws error:

我正在使用 JUnit 来测试 Spring 的组件,抛出错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'wsVehicleService' is defined

This is my test class:

这是我的测试课:

package com.zw.ws.service.impl;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/*.xml")    
public class WsVehicleServiceTest {

    @Autowired
    ApplicationContext ctx;

    @Test
    public void getHistoryAlarmInfo() throws Exception {
        try {
            String requestJson = "\"{\"VEHICLEID\":\"cae21196-cb66-4256-88a6-7cdfb23e2c78\",\"STARTTIME\":1476115200,\"ENDTIME\":1476201599,\"TYPE\":1}\"";
            WsVehicleService vehicleService = (WsVehicleService) ctx.getBean("wsVehicleService");
            vehicleService.getHistoryAlarmInfoImpl(requestJson);
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
}

This is the class will be tested:

这是将要测试的类:

@Component
public class WsVehicleService {

    public List<HistoryAlarmInfo> getHistoryAlarmInfo(String requestJson) {
        try {
            return getHistoryAlarmInfoImpl(requestJson);
        } catch (Exception e) {
            log.error(e);
            return null;
        }
    }
}

When JUnit run to getBean,throws error:No bean named 'wsVehicleService' is defined. Where is going wrong?What could I do to make it right?

当 JUnit 运行到 getBean 时,抛出错误:No bean named 'wsVehicleService' is defined. 哪里出错了?我能做些什么来使它正确?

What I having tried:

我尝试过的:

add @ComponentScan("com.zw.ws.*")to scan the WsVehicleService class.

添加@ComponentScan("com.zw.ws.*")以扫描 WsVehicleService 类。

This is the log:

这是日志:

    12:53:11.098]-[main]-[org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener]-{After test method: context [DefaultTestContext@58783f6c testClass = WsVehicleServiceTest, testInstance = com.zw.ws.service.impl.WsVehicleServiceTest@7577b641, testMethod = getHistoryAlarmInfo@WsVehicleServiceTest, testException = org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'wsVehicleService' is defined, mergedContextConfiguration = [MergedContextConfiguration@3a7b503d testClass = WsVehicleServiceTest, locations = '{classpath:/*.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null], method annotated with @DirtiesContext [false] with mode [null].}

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'wsVehicleService' is defined

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1175)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
    at com.zw.ws.service.impl.WsVehicleServiceTest.getHistoryAlarmInfo(WsVehicleServiceTest.java:27)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="wsVehicleService"
          class="com.mycompany.annotation.WsVehicleService">
      </bean>

</beans>
0(ParentRunner.java:53) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193) at org.junit.runner.JUnitCore.run(JUnitCore.java:160) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:253) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) 12:53:11.107]-[main]-[org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener]-{After test class: context [DefaultTestContext@58783f6c testClass = WsVehicleServiceTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@3a7b503d testClass = WsVehicleServiceTest, locations = '{classpath:/*.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null].}

PS:This is no XML configuration,all beans are using autoscan.

PS:这不是XML配置,所有bean都使用自动扫描。

采纳答案by Unknown

1)First Solution:

1)第一个解决方案:

@ContextConfigurationinitializes the Spring context and by default looks for a Spring XML file in the same package as the unit test with the file name the same as the class with '-context.xml' as a suffix

@ContextConfiguration初始化 Spring 上下文,默认情况下在与单元测试相同的包中查找一个 Spring XML 文件,文件名与带有“-context.xml”作为后缀的类相同

Try adding the WsVehicleServiceTest-context.xml file in com.mycompany.annotationpackage.

尝试在com.mycompany.annotation包中添加 WsVehicleServiceTest-context.xml 文件。

package com.mycompany.annotation;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class WsVehicleServiceTest {

    @Autowired
    ApplicationContext ctx;

    @Test
    public void getHistoryAlarmInfo() throws Exception {
        try {
            WsVehicleService vehicleService = (WsVehicleService) ctx
                    .getBean("wsVehicleService");
            String hi = vehicleService.sayHi();
            System.out.println(hi);
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
}

Junit test class after removing ("classpath:/*.xml"):

删除后的 Junit 测试类(“classpath:/*.xml”):

<bean id="wsVehicleService"
              class="com.mycompany.annotation.WsVehicleService">
</bean>

Note:If you want to use @ContextConfiguration("classpath:/*.xml")make sure you put

注意:如果你想使用,请@ContextConfiguration("classpath:/*.xml")确保你把

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/*.xml")   
public class WsVehicleServiceTest {

    @Autowired
    ApplicationContext ctx;

    @Autowired
    WsVehicleService wsVehicleService;

    @Test
    public void getHistoryAlarmInfo() throws Exception {
        try {
            String hi = wsVehicleService.sayHi();
            System.out.println(hi);
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
}

in any one of your *.xml file

在您的任何一个 *.xml 文件中

2) Second Solution:

2)第二种解决方案:

Make sure you put <context:annotation-config />in your xml file. Here you do not need to declare the wsVehicleService bean in your xml file.

确保你输入<context:annotation-config />了你的 xml 文件。这里不需要在 xml 文件中声明 wsVehicleService bean。

Modify your test class by using @Autowiredon WsVehicleService

使用@Autowiredon修改您的测试类WsVehicleService

package com.mycompany.annotation;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;


@Configuration
@ComponentScan("com.mycompany.annotation")
public class AppConfig {

}

3) Third solution:

3)第三种解决方案:

You have mentioned, you do not use any xml configuration files and your exception tells org.springframework.beans.factory.NoSuchBeanDefinitionException

您已经提到,您不使用任何 xml 配置文件,并且您的异常告诉 org.springframework.beans.factory.NoSuchBeanDefinitionException

One reason your WsVehicleService may not exist in the context – is that it may be defined in a package that is not scanned by Spring.

您的 WsVehicleService 可能不存在于上下文中的一个原因是它可能定义在一个未被 Spring 扫描的包中。

Make sure your WsVehicleService exist in @ComponentScan("com.mycompany.annotation")package.

确保您的 WsVehicleService 存在于@ComponentScan("com.mycompany.annotation")包中。

1) Application configuration class with annotation @Configuration

1)带有@Configuration注解的应用配置类

package com.mycompany.annotation;

import org.springframework.stereotype.Component;

@Component
public class WsVehicleService {
    public String sayHi(){
        return "HI !!!!!!!!!!";
    }
}

2) Your service class

2) 你的服务类

package com.mycompany.annotation;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public class WsVehicleServiceTest {

    @Autowired
    ApplicationContext ctx;

    @Test
    public void getHistoryAlarmInfo() throws Exception {
        try {
            WsVehicleService vehicleService = (WsVehicleService) ctx
                    .getBean("wsVehicleService");
            String hi = vehicleService.sayHi();
            System.out.println(hi);
        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
}

3)Junit test class

3)Junit测试类

HI !!!!!!!!!!

OUTPUT:

输出:

WsVehicleService vehicleService = (WsVehicleService) ctx.getBean(WsVehicleService .class);

For more info you can refer thisand this

有关更多信息,您可以参考这个这个

More reference for causes and possible solution for NoSuchBeanDefinitionException

有关NoSuchBeanDefinitionException 的原因和可能的解决方案的更多参考

回答by kuhajeyan

Change line

换线

@Component("wsVehicleService")
public class WsVehicleService{

//..

}

or

或者

@Configuration
@ComponentScan(basePackages = {"com.zw.ws"})
public class AppTestConfig {}

回答by exoddus

"No bean named 'xxx' is defined" is thrown when:

在以下情况下抛出“未定义名为 'xxx' 的 bean”:

  • Your bean has a different name.
  • Your bean isn't actually in the context.
  • 您的 bean 具有不同的名称。
  • 您的 bean 实际上不在上下文中。

Since you haven't changed the default name of the bean, then must be that the bean isn't properly loaded.

由于您尚未更改 bean 的默认名称,因此必须是 bean 未正确加载。

You need to indicate where are your components to be scanned (xml config or @Configuration class) and be loaded when run your tests. I would create a config class and then add this new config class in the ContextConfiguration annotation (or use xml if you prefer).

您需要指出在运行测试时要扫描的组件(xml 配置或@Configuration 类)和加载的位置。我会创建一个配置类,然后在 ContextConfiguration 注释中添加这个新的配置类(或者,如果您愿意,可以使用 xml)。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AppTestConfig.class}) 
public class WsVehicleServiceTest {
...
}

Your test class then:

你的测试类然后:

//main class    
//@Import(value=AppConfig.class)     
public class AppAnno {   
    public static void main(String[] args) {  
        AnnotationConfigApplicationContext ctx = new  
 AnnotationConfigApplicationContext(AppConfig.class);  
    TodayDate date = ctx.getBean("todayDate",TodayDate.class);   
System.out.println(date.getTodyDate());     
    }     
}    

@Configuration  
@ComponentScan(basePackages={"com.cb.service.anno","com.cb.dao.anno"})  

You can also anotate with @Autowireyour service and let Spring do the wiring work.

您还可以对@Autowire您的服务进行注释,并让 Spring 完成接线工作。

回答by ANiket Chavan

Spring Annotation code

Spring注解代码

public class AppConfig {  
    @Bean 
public Date date(){    
return new Date();   
}    
}  

import java.util.Date;     
import javax.inject.Named;   
import org.springframework.beans.factory.annotation.Autowired;    
import org.springframework.stereotype.Component;   
@Component     
@Named("todayDate")//you have to add inject jar to your build path     
public class TodayDate {      
@Autowired    
    Date date;    
    public String getTodyDate(){     
    return date.toString( );    
    }     
}     

change it according to your basepackage

根据您的基本包进行更改

##代码##