1

I have a problem with Dependency Injection inside an external Jar. The result always is null. I am using spring framework and java8.

My main has the following code:

package com.a.1

@SpringBootApplication
@ComponentScan(basePackages = {"com.b.2"})
@Configuration
public class Main{  ... }

I have a test that call to the library

package com.a.1.test

public class test {

RequestMethod requestMethod = new RequestMethod();
requestMethod.method();

This RequestMethod is in a library (other Jar):

package com.b.2

public class RequestMethod {

@Autowired
private Headers header;

    public String method(){
    ...
    }  
}

The class Headers has the annotation @Service. An always the result is null.

package com.b.2

@Service
public class Headers{
...
}

The problem is that Headers is not being injected in RequestMethod. Could someone explain me how I have to prepare the Spring project to inject this dependecy?

Thank you very much in advanced

1 Answers1

1
  1. RequestMethod sould have a @Service-Annotation.

     package com.b.2
    
     @Service
     public class RequestMethod {
    
     @Autowired
     private Headers header;
    
       public String method(){
        ...
       }  
     }
    
  2. In the Test-Class RequestMethod sould be Autowired.

    package com.a.1.test
    
    public class test {
    
    @Autowired
    RequestMethod requestMethod;
    
  3. Your Test should be a Spring-Test

    package com.a.1.test
    
    @SpringBootTest
    public class test {
    
    @Autowired
    RequestMethod requestMethod;
    
       @Test
        public void test(){
         requestMethod.method();
       }
    
    }
    
Mehtrick
  • 518
  • 3
  • 12
Michael Seiler
  • 650
  • 1
  • 5
  • 15