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

标签 java spring configuration dependency-injection

我为 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/

相关文章:

java - unix 中的多个命令行

java - Tomcat NIO 和 Sendfile 清理文件发送

java - 无法使用上下文 :property-placeholder (Spring) 获取属性

php - 当 PHP 失败时 Apache 回退

asp.net - 什么基准可以测试我的 ASP.NET、SQL Server、IIS 产品的硬件性能?

java - 有人可以解释这个 maven-jar-plugin 配置吗?

java - Eclipse 帮助中的 Postgres JDBC 连接

java - spring mvc 应用程序的正确配置

java - Spring Remoting 中的 RMI 客户端身份验证

c# - 如何模拟 C# 应用程序的配置