我正在嘗試使用註釋的春天mvc中的一個簡單應用程序。在我的服務類中,即使使用了相關注釋,我也無法注入DAO類。請讓我知道我在做什麼錯誤。以下是我的班級定義。無法在簡單彈簧mvc應用程序中注入bean
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SpringRootConfig.class };
//return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfiguration.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.emp.controller")
public class SpringWebConfiguration extends WebMvcConfigurerAdapter{
@Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.emp.svc,com.emp.dao")
public class SpringRootConfig {
}
package com.emp.svc;
import org.springframework.beans.factory.annotation.Autowired;
import com.emp.dao.LoginDAO;
public class LoginSvc {
@Autowired
private LoginDAO dao;
public boolean validateLogin(){
System.out.println("In the svc method");
return dao.validateLogin();
}
}
package com.emp.dao;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
@Repository
public class LoginDAO {
public boolean validateLogin(){
System.out.println("In the DAO method");
return true;
}
}
package com.emp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.emp.forms.LoginForm;
import com.emp.svc.LoginSvc;
@Controller
public class LoginController {
@RequestMapping(value = {"/login"},method = RequestMethod.GET)
public ModelAndView launchLoginPage(){
ModelAndView model = new ModelAndView();
model.setViewName("login");
return model;
}
@RequestMapping(value = {"/welcome"},method = RequestMethod.GET)
public ModelAndView validateLogin(@ModelAttribute LoginForm form){
ModelAndView model = new ModelAndView();
LoginSvc svc = new LoginSvc();
if(svc.validateLogin()){
model.setViewName("welcome");
}
else
{
model.setViewName("login");
}
return model;
}
LoginSvc從控制器調用。我期待在LoginSvc中,LoginDAO將被注入,因此對dao.authateLogin()的調用將會成功。但是我得到的是空指針在dao.validateLogin(),指示LoginDAO不被注入。
如果你能讓我知道我錯過了什麼,這將是很大的幫助。
用'@ controller'註釋來註釋你的'LoginSvc'類。 – hagrawal
我有單獨的控制器類,(我現在已經添加了我的控制器類)應該仍然註釋@controller的svc類? – Anveshan
是的,你應該註釋'LoginSvc'類,以便它成爲控制器,如果你不註釋,那麼spring不會注入依賴項。 – hagrawal