0

I wrote a Spring Application TemporalConfigurationService (TCS) which runs fine with Spring Boot. It is complete code based configured instead using persistence.xml or context.xml. Now I want to use this API as a library in a non Spring Application. If I try to initilize TCS in a test with...

TemporalConfigurationServiceImpl tcs = new TemporalConfigurationServiceApi()

...all innern repositories and other @Autowired variables are null. How can I reuse my TemporalConfigurationService in other projects?

Grimbo
  • 237
  • 2
  • 13
  • 3
    And why shouldn't it... You are creating a new instance yourself, you must let spring create and manage the instance. – M. Deinum May 28 '15 at 12:39
  • 1
    this may not be a good solution but I think it should work. You can load the spring app's context using ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml"); TemporalConfigurationServiceImpl tcs = context.getBean("theBeanName"); – Surely May 28 '15 at 12:40
  • I am surprised that after all these many years still few people didn't understand very basics of Dependency Injection and expect all DI stuff work when they create an Object using new operator!!! – K. Siva Prasad Reddy May 28 '15 at 12:43
  • 1
    You need to load your app context, and then get the bean you need from it. – Krzysztof Cichocki May 28 '15 at 12:46
  • Maybe you're using Spring for years I am just starting! I hoped that Spring Boot would do some "super magic" and it will work without specific Spring DI! – Grimbo May 28 '15 at 12:47
  • in order to enable super magic, you have to use spring :) – gyoder May 28 '15 at 13:47

1 Answers1

0

This is how I solved the problem. Caue my service is complete code based configured I had to extend my ApplicationConfig.java with:

@Bean
public TemporalConfigurationServiceImpl temporalConfigurationServiceImpl() {
    return new TemporalConfigurationServiceImpl();
}

Now I can use my TCS as library in other projects with:

ApplicationContext ctx = new AnnotationConfigApplicationContext(ApplicationConfig.class);
TemporalConfigurationServiceImpl configuration = ctx.getBean(TemporalConfigurationServiceImpl.class);

First I got some wired exceptions, so I had to also remove my Spring Boot Start-class and now it's working! Thx to some commentators and this link: http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm

Grimbo
  • 237
  • 2
  • 13