[英]How can I override configuration in spring using conditional annotations (for example)
[英]How can I programmatically configure Spring's @Configuration annotations?
具體來說,我希望能夠通過實例化並包含它們來共享配置類。 您通常會在哪里執行此操作:
@Configuration
@Import({SharedConfiguration.class})
public class MyAppContext extends WebMvcConfigurerAdapter {
//stuff
}
@Configuration
@ComponentScan("com.example")
public class SharedConfiguration {
//stuff
}
我想這樣做:
@Configuration
public class MyAppContext extends WebMvcConfigurerAdapter {
public SharedConfiguration sharedConfig(){
return new SharedConfiguration("com.example");
}
//stuff
}
@Configuration
public class SharedConfiguration {
public SharedConfiguration(String package){
//tell Spring to scan package
}
}
這樣做的原因是我需要能夠告訴執行掃描的共享組件要查看哪個包。 它會根據它在哪個項目中使用而有所不同。
編輯:
為了提供一些額外的上下文,我正在嘗試使用我們的多個項目可以使用的外部配置提供程序來設置用於設置 Hibernate 和 EHCache 的通用配置。 我當然願意接受其他方法來做到這一點,但這對我來說似乎是最合乎邏輯的途徑。 我確信 Spring 中有一些東西可以讓我擺弄說:“在這里!當 Spring 初始化你時掃描這條路徑!” 而不是將其硬編碼到注釋中。
在這種情況下,您可以利用屬性源。
在測試用例中,我正在設置一個由 Spring 屬性源配置選取的系統屬性 -
@RunWith(SpringRunner.class)
@ContextConfiguration
public class MyAppContextTest {
@Autowired
ApplicationContext context;
@BeforeClass
public static void beforeClass() {
// use a system property to configure the component scan location of the SharedConfiguration
// where the "ExampleBean" lives
System.setProperty("packages", "net.savantly.other.packages");
}
@Test
public void ensureExampleBeanExists() {
// throws exception if it doesnt exist
context.getBean(ExampleBean.class);
}
@Configuration
@Import(MyAppContext.class)
static class TestContext {
}
}
在 ComponentScan 中使用 Spring 表達式語言 -
@Configuration
@ComponentScan("${packages}")
public class SharedConfiguration {}
其他參考類 -
@Configuration
@Import(SharedConfiguration.class)
public class MyAppContext extends WebMvcConfigurerAdapter {
@Autowired
SharedConfiguration sharedConfig;
//stuff
}
@Service
public class ExampleBean {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.