我有一个名为InjectionTest的bean,它用@Component
注释。
当我在控制器内自动装配这个bean时,它工作正常。
但是当我尝试在另一个带有@Component
注释的类中使用它时,autowire不起作用,我得到一个空指针异常。有任何想法吗 ?
InjectionTest类
@Component
public class InjectionTest {
private String word;
public String getWord() {
return "test";
}
public void setWord(String word) {
this.word = word;
}
}
下面是控制器类方法,它可以正常工作
@Controller
@CrossOrigin(origins = "*")
public class UserController {
@Autowired
AppConfig appConfig;
@Autowired
InjectionTest injectionTest;
@RequestMapping(value = "/api/user/authentication", method = RequestMethod.POST)
@ResponseBody
public String authentication(HttpServletResponse res, @RequestParam Map<String, String> allRequestParams,
HttpServletRequest req) {
//I dont get an exception in the below line it works fine..
System.out.println(injectionTest.getWord());
....
}
}
下面是我想要自动装配InjectionTest类并在创建时获取空指针异常的组件......
@Component
public class HelloComponent {
@Autowired
InjectionTest injectionTest;
public HelloComponent(){
//I get null pointer exception in the below line.
injectionTest.getWord();
}
}
严重:StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException:错误 创建名为&#39; helloComponent&#39;的bean在文件中定义 [C:\ Repo.metadata.plugins \ org.eclipse.wst.server.core \ TMP3 \ wtpwebapps \ AdaRvmWeb \ WEB-INF \类\ TR \ COM \ simroll \阿达\ RVM \网络\实体\ HelloComponent.class] : bean的实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:失败 实例化[tr.com.simroll.ada.rvm.web.entity.HelloComponent]: 构造函数抛出异常;嵌套异常是 显示java.lang.NullPointerException
我真的很困惑。创作时是否有订单或其他内容。如果是这样,我该如何解决这个问题呢?感谢..