简体   繁体   中英

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).

What is the shortest path from having a PropertyResolver and an annotated class that wants @Value s injected to an autowired bean instance?

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).

Create a separate configuration, that only has the beans you want:

@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 :

public static void main(String[] args) {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
    TheBean myService = ctx.getBean(TheBean.class);
    myService.doStuff();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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