【问题标题】:How to avoid BeanCreationException: Could not autowire field error如何避免 BeanCreationException:无法自动装配字段错误
【发布时间】:2015-03-27 09:21:32
【问题描述】:

我有以下具有不同配置文件的弹簧测试配置:

@Configuration
@ComponentScan (value = {"uk.co.test.ws" })
public class SpringTestConfig
{


    @Profile( "local")
    @PropertySource( "classpath:/config/local/settings.properties" )
    public static class SpringTestConfigLocal
    {
        @Autowired
        private Environment environment ;  

        @Bean(name= "baseUrl" )
        public String setBaseUrl()
        {
            return environment .getRequiredProperty("baseurl.protocol" )+"://" +environment .getRequiredProperty( "baseurl.host");             
        }
    }

然后创建了一个基类,该基类接受基 url

> @RunWith (SpringJUnit4ClassRunner. class) @ContextConfiguration
> (classes = { SpringTestConfig. class }) public class BaseWsTest {
>     @Autowired
>     String baseUrl;

然后扩展到其他测试类,如下所示:

public class SampleFTest extends BaseWsTest
{
    @Test
    public void hello() throws FileNotFoundException, Exception
    {
        System. out .println("base url: " + baseUrl );

当使用普通的 maven clean install 运行时,测试可以工作,但是如果我通过右键单击该方法来运行它,它会得到一个

Error creating bean with name 'uk.co.test.ws.service.base.SampleFTest': Injection of autowired dependencies failed;

【问题讨论】:

  • “通过右键单击”我猜在某些 IDE 中?如果是这样,您应该在 IDE 中检查此任务的配置。
  • 是的,在 eclipse 上,抱歉我忘了提。右键单击运行“JUnit 测试”。它应该有什么配置?我在 vm 参数中添加了 -Dspring.profile.active=local ,但它仍然不起作用..
  • 您是否只有消息“自动装配依赖注入失败;”或者你可以看到完整的堆栈跟踪?通常春天也会显示失败的原因。 “找不到豆子”或类似的东西。根据此消息,您可以了解需要在 JUnit 任务的配置中添加什么。
  • 嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:java.lang.String uk.co.gamma.gnp.ws.service.base.GnpWsTest.baseUrl;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type of [java.lang.String] found for dependency: 预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
  • 这些是完全的例外。我忘了怎么做,所以堆栈跟踪在stackoverflow评论中看起来更清晰抱歉。

标签: java spring testing junit autowired


【解决方案1】:

您忘记在SampleFTest 课程中选择个人资料,您应该添加以下行:

@ActiveProfiles(profiles = "local")

这样SpringTestConfigLocal 将被初始化并且baseUrl bean 可用

编辑:我会在.properties 文件中添加一个属性,这样我就可以使用变量myprofile:

@ActiveProfiles(profiles = "${myprofile}")

最终,如果您不想不时更改值,我会应用一些逻辑来加载一个或另一个属性文件。

编辑 2:很抱歉,这不起作用,因为文件是在分配注释 EL 值之后加载的,但您可以添加以下内容:

spring.profiles.active=local

到属性文件,这将与添加注释@IntegrationTest("local") 相同。这是我试过的代码:

@TestPropertySource(value="classpath:/config/test.properties")//, properties={"myaddress=cane", "myprofile=local"})
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("${myaddress}")
//@ContextConfiguration
//@ActiveProfiles(profiles = "${myprofile}")
public class BasicJUnitTest{

    protected Logger logger;

    protected MockMvc mockMvc;

    @Autowired
    private Environment env;

    
    @Value("${myaddress}" )
    String myval;
    
    
    public BasicJUnitTest(){
        this.logger = LoggerFactory.getLogger(this.getClass());
    }
        
    @Test
    public void test(){
        logger.info("hola"+myval+ " " + env.getActiveProfiles()[0]);
    }
    

}

【讨论】:

  • 哦,哇,好用,谢谢。有没有办法让它使用 pom.xml 中的配置文件?我想要它,这样我就可以用特定的配置文件编译测试,所以我不必不断改变那行。
  • 我不知道如何使用 pom.xml 中的变量,但我会使用我在编辑中编写的属性文件
  • 谢谢。我已经尝试将它添加到我的 settings.properties 文件中,但它没有被拾取
  • 您是否在测试中添加了@TestPropertySource("/your_properties.properties")
  • 我把它放在@Act​​iveProfiles 注释的正上方,不幸的是它仍然不起作用。可以举个例子吗?
猜你喜欢
  • 1970-01-01
  • 2012-05-19
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-07
  • 2014-09-07
  • 1970-01-01
相关资源
最近更新 更多