我为 Spring Boot 应用程序编写了一些代码,现在我想在 Spring Boot 之外重用这些代码(用于独立的命令行工具)。
拥有 PropertyResolver
和希望将 @Value
注入(inject)到 Autowiring 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,如 the documentation 中所述。 :
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
TheBean myService = ctx.getBean(TheBean.class);
myService.doStuff();
}
关于java - 如何独立于 Spring 上下文使用 @Autowired 和 @Value 注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28207792/