Я пытаюсь создать приложение Hello World, используя Spring MVC и JavaConfigs вместо файлов XML. Я читал, что вы можете объявить bean-компонент с помощью @Bean, если класс аннотирован с помощью @Configuration. У меня есть класс, аннотированный @Configuration, и метод внутри, аннотированный @Bean.
Я получаю сообщение об ошибке в IntelliJ 12 (красная ошибка подчеркивания):
Методы @Bean действительны, только если они объявлены в аннотированном классе @Configuration.
И следующее сообщение об ошибке при запуске Tomcat 7.0.37:
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [S:\dropbox\Shared Folders\Majerus Eric (BBY)\SpringMVCBarebones\target\SpringMVCBarebones\WEB-INF\classes\com\springapp\mvc\WebAppConfig.class]; nested exception is java.lang.annotation.AnnotationFormatError: Invalid default: public abstract org.springframework.beans.factory.annotation.Autowire org.springframework.config.java.annotation.Bean.autowire()
Конфигурация веб-приложения
package com.springapp.mvc;
import org.springframework.config.java.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@EnableWebMvc
@ComponentScan("com.springapp.mvc")
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
}
Инициализатор веб-приложения
package com.springapp.mvc;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
// Create the 'root' Spring application context.
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
// Manage the lifecycle of the root application context.
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(WebAppConfig.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
В качестве примера я использовал это руководство: Перенесите Spring MVC servlet.xml в Java Config, а также документацию Spring по WebAppInitializer.
Мой репозиторий git размещен на Bitbucket здесь.
public class WebAppInitializer implements WebApplicationInitializer
, который я настроил с помощью документация Spring. Если я пытаюсь запустить tomcat, я получаюSEVERE: Context initialization failed ... Failed to read candidate component class: file [ ... \com\springapp\mvc\WebAppConfig.class];
- person Eric Majerus   schedule 12.02.2014