存在注释:在测试中仍然没有找到bean

时间:2014-05-01 20:02:33

标签: java spring

班级

@Component
public class PropertyReader {

    public PropertyReader() {
    }

    @Value("${spring.active.profiles")
    private String profile;

    @Nonnull
    public String getProfile() {
        return profile;
    }
}

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)

public class PropertyReaderTest {

    @Autowired
    private PropertyReader propertyReader;
    @Test
    public void testGetProfile() throws Exception {
        System.out.printf(System.getProperty("spring.active.profiles"));
        assertEquals("development", propertyReader.getProfile());
    }
}

依赖

     <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.3.RELEASE</version>
        </dependency>
    </dependencies>
   <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.0.3.RELEASE</version>
            <scope>test</scope>
        </dependency>

测试失败

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.yahoo.pryme_services.external_services.ifs.PropertyReader com.yahoo.pryme_services.external_services.ifs.PropertyReaderTest.propertyReader; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.yahoo.pryme_services.external_services.ifs.PropertyReader] 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)}

我错过了什么?

P.S。春天的一天

1 个答案:

答案 0 :(得分:-1)

固定

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = PropertyReader.class,loader=AnnotationConfigContextLoader.class)

public class PropertyReaderTest {

    @Autowired
    private PropertyReader propertyReader;
    @Test
    public void testGetProfile() throws Exception {
        System.out.printf(System.getProperty("spring.active.profiles"));
        assertEquals("development", propertyReader.getProfile());
    }
}

@Component
public class PropertyReader {

    public PropertyReader() {
    }

    @Value("#{systemProperties['spring.active.profiles']}")
    private String profile;

    @Nonnull
    public String getProfile() {
        return profile;
    }
}