简体   繁体   English

在导入的spring @Configuration中解析@Value

[英]resolving @Value in imported spring @Configuration

I have changed the original answer, because it was not complete. 我已经更改了原始答案,因为它不完整。 The updated answer follows here: 更新后的答案如下:

I would like to autowire Resource file in the test @Configuration. 我想在测试@Configuration中自动装配资源文件。 The scenario is as follows: 场景如下:

@RunWith(SpringRunner.class)                                                                                                                                             
@ContextConfiguration(classes = TestConfiguration.class)                                                                                                                 
public class FooTest {                                                                                                                                                   

    @Test                                                                                                                                                                
    public void foo() {                                                                                                                                                  
    }                                                                                                                                                                    
}                                                                                                                                                                        


@Slf4j
@Configuration
public class TestConfiguration extends BaseConfiguration {

    @Value("classpath:derby-db.sql")
    private Resource dbScript;

    @Bean
    public Object foo() {
        log.info("{}", dbScript);
        return new Object();
    }

    @Override
    protected Object getFoo() {
        return foo;
    }
}


public abstract class BaseConfiguration {

    @Autowired
    @Qualifier("foo")
    protected Object foo;

    protected abstract Object getFoo();
}

However, the scenario does not work. 但是,该方案不起作用。 Reference to the dbScript is null while initializing bean foo . 初始化bean foo时,对dbScript为null。 If I move the protected autowired field named foo out of BaseConfiguration and put it to the top-level TestConfiguration , everything works as expected and the dbScript reference is initialized. 如果我将名为foo的受保护的自动装配字段移出BaseConfiguration并将其放置到顶级TestConfiguration ,则一切都会按预期进行,并且dbScript引用已初始化。

Could someone please explain this behaviour? 有人可以解释一下这种行为吗?

Thanks for reply. 谢谢您的回复。

Miro 米罗

@Value annotation is used to inject value of a property. @Value批注用于注入属性的值。 If you want to initialize Resource object then use @PropertySource(value="classpath:xxxxx.properties") annotation above class name. 如果要初始化Resource对象,请在类名上方使用@PropertySource(value =“ classpath:xxxxx.properties”)批注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM