在SpringMVC和JavaConfig中使用@Autowired
我有SpringMVC项目,我没有使用@Autowired,因为我的对象总是空的。如何使用@Autowired加载JavaConfig,我不使用任何*.xml文件 这是我的控制器,带有@Autowired field for service在SpringMVC和JavaConfig中使用@Autowired,java,spring-mvc,spring-java-config,Java,Spring Mvc,Spring Java Config,我有SpringMVC项目,我没有使用@Autowired,因为我的对象总是空的。如何使用@Autowired加载JavaConfig,我不使用任何*.xml文件 这是我的控制器,带有@Autowired field for service @Controller public class WebController { @Autowired private ServiceWeb serviceWeb; public void setServiceWeb(Service
@Controller
public class WebController {
@Autowired
private ServiceWeb serviceWeb;
public void setServiceWeb(ServiceWeb serviceWeb) {
this.serviceWeb = serviceWeb;
}
...
}
这是我的AbstractAnnotationConfigDispatcherServletInitializer
@Autowiring的类
为spring注册上下文,但在哪里需要写Init.class来加载此配置
public class Init implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ConfigurationBean.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
}
}
请试试这个
@Service
public class ServiceWebImpl implements ServiceWeb {
}
ServiceWebBean是在ConfigurationBean类中创建的,它在spring上下文级别上对于自动连接不可见。这并不能回答这个问题。若要评论或要求作者澄清,请在其帖子下方留下评论。同意您的观点@Fabio,但我根据上述观察结果提出了我的答案。
@Configuration
public class ConfigurationBean {
@Bean
public ServiceWeb serviceWeb(){
return new ServiceWebImpl();
}
}
public class Init implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ConfigurationBean.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
}
}
@Service
public class ServiceWebImpl implements ServiceWeb {
}