如何避免BeanCreationException:无法自动装配字段错误

时间:2015-03-27 09:21:33

标签: java spring testing junit autowired

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

@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;

1 个答案:

答案 0 :(得分:0)

您忘了在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]);
    }


}