【问题标题】:How can I make use of @Autowired and @Value annotations independent of Spring context?如何独立于 Spring 上下文使用 @Autowired 和 @Value 注释?
【发布时间】:2015-01-29 05:50:13
【问题描述】:

我为 Spring Boot 应用程序编写了一些代码,现在我想在 Spring Boot 之外重用(用于独立命令行工具)。

PropertyResolver 和一个希望@Values 注入自动装配的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 服务器应用程序)。

【问题讨论】:

  • 创建另一个更轻量级的 Spring 配置,它只有 PropertyResolver 作为 bean,以及您自己的 bean?
  • 听起来像是一个计划。但是怎么做呢?

标签: java spring configuration dependency-injection


【解决方案1】:

创建一个单独的配置,只包含您想要的 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 2013-02-09
    • 1970-01-01
    • 2016-03-08
    • 1970-01-01
    相关资源
    最近更新 更多