Создание application context в веб приложении spring
- User
Создание application context в веб приложении spring
- Assistant
Создание application context в веб приложении spring
Веб приложение Spring создает свой контекст приложения при инициализации контейнера сервлетов. Для создания собственного application context в веб приложении Spring, необходимо создать класс, который будет расширять класс AbstractAnnotationConfigDispatcherServletInitializer и переопределить методы getRootConfigClasses() и getServletConfigClasses().
Пример создания класса:
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Здесь AppConfig и WebConfig - это конфигурационные классы, в которых определяются бины и настройки для приложения.
AppConfig может выглядеть примерно так:
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}
WebConfig может выглядеть примерно так:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
}
После создания класса MyWebAppInitializer, необходимо добавить его в каталог WEB-INF и указать его в файле web.xml:
<web-app>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>config.MyWebAppInitializer</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Теперь приложение будет использовать созданный application context для инициализации бинов и конфигураций.
Not yet included in a published release.