Thilo
Thilo

Reputation: 262504

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

Upvotes: 1

Views: 467

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

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();
}

Upvotes: 2

Related Questions