简体   繁体   English

如何独立于Spring上下文使用@Autowired和@Value批注?

[英]How can I make use of @Autowired and @Value annotations independent of Spring context?

I have some code written for a Spring Boot application that I now want to reuse outside of Spring Boot (for standalone command line tools). 我为Spring Boot应用程序编写了一些代码,现在我想在Spring Boot之外重用(对于独立的命令行工具)。

What is the shortest path from having a PropertyResolver and an annotated class that wants @Value s injected to an autowired bean instance? PropertyResolver和带注释的类想要将@Value注入自动装配的bean实例的最短路径是什么?

For example, if I have a constructor 例如,如果我有一个构造函数

 @Autowired
 public TheBean(@Value("${x}") int a, @Value("${b}") String b){}

and I already set up (dynamically, in code) 并且我已经设置好了(用代码动态地)

 PropertyResolver props; 

how can I make use of all this annotations so that I don't have to write the very explicit and repetitive 我该如何利用所有这些注释,这样我就不必写非常明确和重复的内容

TheBean bean = new TheBean(
     props.getProperty("x", Integer.TYPE), 
     props.getProperty("y"));

I have the complete Spring Boot application (including Spring dependencies) on the classpath, but Spring has not been initialized (no call to SpringApplication#run , because that would bring up the whole web server application). 我在类路径上具有完整的Spring Boot应用程序(包括Spring依赖项),但是Spring尚未初始化(不调用SpringApplication#run ,因为那样会弹出整个Web服务器应用程序)。

Create a separate configuration, that only has the beans you want: 创建一个单独的配置,仅包含所需的bean:

@Configuration
@PropertySource("classpath:/com/myco/app.properties")
@ComponentScan("com.myco.mypackage")
public class AppConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

And then instantiate a Spring context and get the bean from it as explained in the documentation : 然后实例化一个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.

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