Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在SpringMVC和JavaConfig中使用@Autowired_Java_Spring Mvc_Spring Java Config - Fatal编程技术网

在SpringMVC和JavaConfig中使用@Autowired

在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

我有SpringMVC项目,我没有使用@Autowired,因为我的对象总是空的。如何使用@Autowired加载JavaConfig,我不使用任何*.xml文件

这是我的控制器,带有@Autowired field for 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 {

}