我在外部Jar中遇到了依赖注入问题。结果始终为null。我使用的是spring框架和java8。
我的主要代码如下:
package com.a.1
@SpringBootApplication
@ComponentScan(basePackages = {"com.b.2"})
@Configuration
public class Main{ ... }
我有一个调用库的测试
package com.a.1.test
public class test {
RequestMethod requestMethod = new RequestMethod();
requestMethod.method();
此RequestMethod位于库(其他Jar)中:
package com.b.2
public class RequestMethod {
@Autowired
private Headers header;
public String method(){
...
}
}
类Headers具有注释@Service。总是结果是null。
package com.b.2
@Service
public class Headers{
...
}
问题是Header没有被RequestMethod注入。有人可以解释一下我如何准备Spring项目以注入这种依赖性吗?
非常感谢先进的
答案 0 :(得分:1)
RequestMethod
应该有@Service
- 注释。
package com.b.2
@Service
public class RequestMethod {
@Autowired
private Headers header;
public String method(){
...
}
}
在测试班RequestMethod
中应该是Autowired
。
package com.a.1.test
public class test {
@Autowired
RequestMethod requestMethod;
您的测试应该是一个Spring-Test
package com.a.1.test
@SpringBootTest
public class test {
@Autowired
RequestMethod requestMethod;
@Test
public void test(){
requestMethod.method();
}
}