我有spring mvc项目,我不使用@Autowired
,因为我的对象始终是null
。如何使用JavaConfig
加载@Autowired
,我不使用任何* .xml文件。
这是我的控制器,其中@Autowired
字段用于服务。
@Controller
public class WebController {
@Autowired
private ServiceWeb serviceWeb;
public void setServiceWeb(ServiceWeb serviceWeb) {
this.serviceWeb = serviceWeb;
}
...
}
这是我的 AbstractAnnotationConfigDispatcherServletInitializer
public class ServletInit extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { SpringRootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringWebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
SpringRootConfig&amp; SpringWebConfig
@Configuration
@ComponentScan({"web.controller"})
public class SpringRootConfig {
}
@EnableWebMvc
@Configuration
@ComponentScan({ "web.controller"})
@Import({SecurityConfig.class})
public class SpringWebConfig extends WebMvcConfigurerAdapter{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver
= new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
@Autowiring
的等级
@Configuration
public class ConfigurationBean {
@Bean
public ServiceWeb serviceWeb(){
return new ServiceWebImpl();
}
}
注册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);
}
}
答案 0 :(得分:0)
请试试这个......
@Service
public class ServiceWebImpl implements ServiceWeb {
}
ServiceWeb bean在ConfigurationBean类中创建,在弹簧上下文级别不可见,用于自动装配。