我正在开发一个 Spring-MVC 应用程序,我在其中 Autowiring 一个字段,但它被设置为 NULL。我在网上检查了同样问题的解决方案,正如他们所描述的那样,我不应该在工作时创建一个新的类实例,而是从 spring 中获取它。我也试过了,但它总是提示找不到资源。
这是类(class):
@Service
@Transactional
public class GoogleAuthorization{
@Autowired
private DriveQuickstart driveQuickstart; // This guy is null
public void saveCredentials(final String authCode) throws IOException {
GoogleTokenResponse response = flow.newTokenRequest(authCode).setRedirectUri(CALLBACK_URI).execute();
Credential credential = flow.createAndStoreCredential(response, null);
System.out.println(" Credential access token is "+credential.getAccessToken());
System.out.println("Credential refresh token is "+credential.getRefreshToken());
// It fails at below point.
this.driveQuickstart.storeCredentials(credential);
}
Controller 代码:
@RequestMapping(value = "/getgooglelogin")
public String getGoogleLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session,Model model) {
/* ApplicationContext applicationContext = new ClassPathXmlApplicationContext("../WEB-INF/spring/root-context.xml");
GoogleAuthorization helper = (GoogleAuthorization) applicationContext.getBean("helper");*/
GoogleAuthorization helper = new GoogleAuthorization();
}
如上所示,我尝试通过 root-context.xml 获取它,但无论我放置什么路径,它都找不到。
DriveQuickStartImpl:
@Service
@Transactional
public class DriveQuickstartImpl implements DriveQuickstart{
// All these below guys work just fine.
@Autowired
private PersonService personService;
@Autowired
private GoogleDriveService googleDriveService;
@Autowired
private GroupAttachmentsService groupAttachmentsService;
@Autowired
private GroupAccountService groupAccountService;
}
我做错了什么。你能帮忙的话,我会很高兴。多谢。
更新
root-context.xml 所属的图像:
最佳答案
只需 Autowiring GoogleAuthorization 助手(您可以这样做,因为您已经在 Spring 管理的 Controller 中):
@Service
@Transactional
public class DriveQuickstartImpl implements DriveQuickstart{
// Other stuff...
@Autowired
private GoogleAuthorization helper;
@RequestMapping(value = "/getgooglelogin")
public String getGoogleLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session,Model model) {
// use "helper"
}
如果您 Autowiring 帮助程序,它将由 Spring 注入(inject)和管理。所以 Spring 将正确地构建和 Autowiring 它。
关于java - Spring : Autowired bean is null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31288487/