Я пытаюсь создать приложение Hello World с использованием Spring MVC и JavaConfigs вместо XML-файлов. Я прочитал, что вы можете объявить bean-компонент, используя @Bean, если класс аннотируется с @Configuration. У меня есть класс, аннотированный с @Configuration и метод внутри, аннотированный с @Bean.«Методы @Bean действительны только при объявлении в классе @Configuration annotated» error
Я получаю сообщение об ошибке в 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()
WebAppConfig
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;
}
}
WebAppInitializer
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("/");
}
}
В качестве примера, я использовал этот учебник: Migrate Spring MVC servlet.xml to Java Config, а также пружинные документацию по WebAppInitializer.
My git repo размещен на Bitbucket here.
Опубликованный код здесь прекрасно работает, используя 3.2.6.RELEASE. Какую версию весны вы используете? Вы используете @Bean где-нибудь еще в своем коде? –
@SheenaArtrip Я использую 3.2.6.RELEASE тоже. Это единственный @Bean. Мой другой класс - «открытый класс WebAppInitializer реализует WebApplicationInitializer», который я сконфигурировал с помощью [Spring documentation] (http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/web/WebApplicationInitializer .html). Если я пытаюсь запустить tomcat, я получаю «SEVERE: Ошибка инициализации контекста» ... Не удалось прочитать класс кандидата компонентов: файл [... \ com \ springapp \ mvc \ WebAppConfig.class]; ' –
Это тоже хорошо работает. Также отправьте свой WebApplicationInitializer. В каком контейнере вы работаете? Как выглядит ваш удаленный импорт? –