[英]How can I make use of @Autowired and @Value annotations independent of Spring context?
我為Spring Boot應用程序編寫了一些代碼,現在我想在Spring Boot之外重用(對於獨立的命令行工具)。
將PropertyResolver
和帶注釋的類想要將@Value
注入自動裝配的bean實例的最短路徑是什么?
例如,如果我有一個構造函數
@Autowired
public TheBean(@Value("${x}") int a, @Value("${b}") String b){}
並且我已經設置好了(用代碼動態地)
PropertyResolver props;
我該如何利用所有這些注釋,這樣我就不必寫非常明確和重復的內容
TheBean bean = new TheBean(
props.getProperty("x", Integer.TYPE),
props.getProperty("y"));
我在類路徑上具有完整的Spring Boot應用程序(包括Spring依賴項),但是Spring尚未初始化(不調用SpringApplication#run
,因為那樣會彈出整個Web服務器應用程序)。
創建一個單獨的配置,僅包含所需的bean:
@Configuration
@PropertySource("classpath:/com/myco/app.properties")
@ComponentScan("com.myco.mypackage")
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
然后實例化一個Spring上下文,並按照文檔中的說明從中獲取bean:
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
TheBean myService = ctx.getBean(TheBean.class);
myService.doStuff();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.