Inherit Spring configuration from another WAR - java

We have a SpringMVC project called "Framework" in Eclipse and a "New project" that must inherit from the "Framework" configuration.
Both Spring projects are not using .xml configuration files.
The "Framework" contains all business classes, datasource configuration and ContextListener default behavior that we don't want to rewrite each time we start a new project.
The "Framework" is loaded as a Maven overlay in the second project.
As you can see below, it is a very basic sample SpringMVC configuration.
Framework
-- main
-- java
-- config
- AppConfig.class (implements WebMvcConfigurer)
- AppInit.class (implements WebApplicationInitializer)
AppConfig.class
#EnableAspectJAutoProxy
#EnableWebMvc
#ComponentScan(basePackages="main.java")
public class AppConfig implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ControllerLoggingInterceptor()).addPathPatterns("/*");
}
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/images/**").addResourceLocations("/resources/images");
}
#Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:messages","classpath:/framework/messages");
return messageSource;
}
#Bean
public javax.validation.Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
#Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(838860800);
return multipartResolver;
}
}
AppInit.class
public class AppInit implements WebApplicationInitializer {
#Autowired
MapperInfosDB mapperUserBD;
#Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(AppConfig.class);
container.addListener(new ContextLoaderListener(appContext));
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(AppConfig.class);
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.addMapping("/");
FilterRegistration.Dynamic fr = container.addFilter("encodingFilter", new CharacterEncodingFilter());
fr.setInitParameter("encoding", "UTF-8");
fr.setInitParameter("forceEncoding", "true");
fr.addMappingForUrlPatterns(null, false, "/*");
fr = container.addFilter("RequestLoggingFilter", new RequestLoggingFilter());
fr.addMappingForUrlPatterns(null, true, "/*");
}
}
In the second project, I import the "Framework" application context successfully, but yet haven't managed to import the WebApplicationContext as it leads to a NullPointerException.
New project
-- main
-- java
-- config
- ApplicationContextConfiguration.class (extends ContextLoaderListener implements WebMvcConfigurer)
- WebConfiguration.class (implements WebApplicationInitializer)
ApplicationContextConfiguration.class
#Configuration
#EnableWebMvc
#EnableAspectJAutoProxy
public class ApplicationContextConfiguration extends ContextLoaderListener implements WebMvcConfigurer {
#Override
protected ApplicationContext loadParentContext(ServletContext servletContext) {
ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
// Do some stuff on applicationContext inherited from Framework
return ac;
}
}
WebConfiguration.class
#Configuration
public class WebConfiguration implements WebApplicationInitializer {
private static final String[] BASE_PACKAGE = { "main.java", "new.project.packages" };
#Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.scan(BASE_PACKAGE);
dispatcherContext.register(AppConfig.class);
dispatcherContext.register(AppInit.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.addMapping("/");
dispatcher.setLoadOnStartup(1);
FilterRegistration.Dynamic fr = container.addFilter("encodingFilter", new CharacterEncodingFilter());
fr.setInitParameter("encoding", "UTF-8");
fr.setInitParameter("forceEncoding", "true");
fr.addMappingForUrlPatterns(null, false, "/*");
fr.addMappingForUrlPatterns(null, true, "/*");
}
}
The StackTrace shows :
Caused by: java.lang.NullPointerException
at main.java.config.AppInit.onStartup(AppInit.java:50)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:172)

You will have to import Config classes in your current config:
import org.springframework.context.annotation.*;
#EnableAspectJAutoProxy
#EnableWebMvc
#ComponentScan(basePackages="main.java")
#Import({WebConfiguration.class, ApplicationContextConfiguration.class })
public class AppConfig implements WebMvcConfigurer {
//Your current configuration
}

Related

Why are WebMvcConfigurer override methods not working?

I created a project with Spring Boot. I am configuring the basic config, but there is a problem in implementing WebMvcConfigurer.
addInterceptors works well, but addViewControllers and addResourceHandlers don't work. There are no errors, but these two methods don't apply.
I think I set it all right, but I can not find the cause. Can I see why?
[Project Structure]
java
--me
----eastglow
------sample
--------controller
----------SampleController.java
------config
--------RootContextConfig.java
--------Application.java
--------DispatcherServletConfig.java
[RootContextConfig.java]
#Configuration
#ComponentScan(
basePackages = {"me.eastglow.*"},
excludeFilters = {#Filter(Controller.class)}
)
public class RootContextConfig {
}
[Application.java]
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Override
public void onStartup(ServletContext container) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootContextConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(DispatcherServletConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("appServlet", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.json");
dispatcher.addMapping("*.do");
}
}
[DispatcherServletConfig.java]
#Configuration
#ComponentScan(
basePackages={"me.eastglow.*"},
useDefaultFilters = false,
includeFilters={#Filter(Controller.class)},
excludeFilters={#Filter(Service.class), #Filter(Repository.class)}
)
#EnableWebMvc
#PropertySource(
value={"classpath:application-${spring.profiles.active}.properties", "classpath:log4jdbc.log4j2.properties"},
ignoreResourceNotFound = true)
public class DispatcherServletConfig implements WebMvcConfigurer {
private final static String[] RESOURCE_HANDLER_PATH = {"/favicon.ico"
, "/image/**"
, "/js/**"};
private final static String[] RESOURCE_HANDLER_LOCATION = {"/resources/favicon.ico"
, "/resources/image/"
, "/resources/js/"};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
CacheControl cacheControl = CacheControl.empty().cachePrivate();
registry.addResourceHandler(RESOURCE_HANDLER_PATH).addResourceLocations(RESOURCE_HANDLER_LOCATION).setCacheControl(cacheControl);
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/member/login.do");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new BusinessInterceptor()).addPathPatterns("/**");
}
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
List<ViewResolver> resolvers = new ArrayList<>();
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
resolvers.add(internalResourceViewResolver);
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setViewResolvers(resolvers);
resolver.setContentNegotiationManager(manager);
return resolver;
}
}
[Updated]
public class DispatcherServletConfig implements WebMvcConfigurer {
private final static String[] RESOURCE_HANDLER_PATH = {"/favicon.ico"
, "/image/**"
, "/js/**"};
private final static String[] RESOURCE_HANDLER_LOCATION = {"/resources/favicon.ico"
, "/resources/image/"
, "/resources/js/"};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
CacheControl cacheControl = CacheControl.empty().cachePrivate();
registry.addResourceHandler(RESOURCE_HANDLER_PATH).addResourceLocations(RESOURCE_HANDLER_LOCATION).setCacheControl(cacheControl);
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/member/login.do");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new BusinessInterceptor()).addPathPatterns("/**");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new FormHttpMessageConverter());
converters.add(jacksonMessageConverter()); //Json Message Converter
converters.add(new StringHttpMessageConverter());
converters.add(new ResourceHttpMessageConverter()); // File Transfer Message Converter
}
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
List<ViewResolver> resolvers = new ArrayList<>();
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
internalResourceViewResolver.setOrder(2);
resolvers.add(internalResourceViewResolver);
JsonViewResolver jsonViewResolver = new JsonViewResolver();
resolvers.add(jsonViewResolver);
resolvers.add(beanNameViewResolver());
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setViewResolvers(resolvers);
resolver.setContentNegotiationManager(manager);
return resolver;
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer configurer = new TilesConfigurer();
configurer.setDefinitions(new String[]{"/WEB-INF/tiles/tiles.xml"});
configurer.setCheckRefresh(true);
return configurer;
}
#Bean
public TilesViewResolver tilesViewResolver() {
TilesViewResolver viewResolver = new TilesViewResolver();
viewResolver.setOrder(1);
return viewResolver;
}
class JsonViewResolver implements ViewResolver {
#Override
public View resolveViewName(String viewName, Locale locale) {
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setPrettyPrint(true);
view.setContentType("application/json;charset=UTF-8");
view.setDisableCaching(true);
return view;
}
}
#Bean(name="beanNameViewResolver")
public BeanNameViewResolver beanNameViewResolver(){
BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver();
beanNameViewResolver.setOrder(0);
return beanNameViewResolver;
}
#Bean(name="jacksonMessageConverter")
public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
return new MappingJackson2HttpMessageConverter();
}
#Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
You are working around Spring Boot instead of using it.
For starters remove the onStartup method of your Application class. Spring Boot takes care of all of that.
Next ditch your RootContextConfig.
2 cleanup your DispatcherServletConfig
#Configuration
#PropertySource(
value={"classpath:log4jdbc.log4j2.properties"},
ignoreResourceNotFound = true)
public class DispatcherServletConfig implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/member/login.do");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new BusinessInterceptor());
}
}
Now in your application.properties (or create one) add the following
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
spring.resources.cache.cache-private=true
The mappings should work by default else place your js and images inside src/main/resources/static or src/main/resources/public.
This is all you need if you properly use Spring Boot (instead of working around it).

404Not Found error returned for Spring REST calls

I am trying to expose my existing web application through web services. For this I have created a REST controller to handle rest calls. I am not sure if I need to change the existing web configurations for web services to work. Below is the URL I am using to access the resources.
http://localhost:9090/HospitalProject/rest/patient/Solo100
#RestController
#RequestMapping("/rest/patient")
public class PatientRESTController {
#RequestMapping(path="/{name}", produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Patient> getPatientByName(#PathVariable("name") String name){
Patient patient = patientService.findPatient(name);
return new ResponseEntity<Patient>(patient, HttpStatus.OK);
}
}
public class ApplicationIntializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext springContext= new AnnotationConfigWebApplicationContext();
springContext.register(ApplicationConfig.class);
springContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(springContext));
dispatcherServlet.setLoadOnStartup(1);
dispatcherServlet.addMapping("/");
}
}
#Configuration
#ComponentScan(basePackages={"com.hp"})
#EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
}

My Spring Application is running but css, js, and images are not being loaded

I have a problem with my Spring app that i'm deploying at OpenShift. Everything seems to be working except my static resource files (css, js, images). I'm getting the following error:
2015-12-11 12:46:31,302 WARN [org.springframework.web.servlet.PageNotFound] (de
fault task-2) No mapping found for HTTP request with URI [/resource/js/jquery-1.
11.3.min.js] in DispatcherServlet with name 'springDispatcher'
2015-12-11 12:46:31,395 WARN [org.springframework.web.servlet.PageNotFound] (de
fault task-3) No mapping found for HTTP request with URI [/resource/js/example.j
s] in DispatcherServlet with name 'springDispatcher'
2015-12-11 12:46:31,419 WARN [org.springframework.web.servlet.PageNotFound] (de
fault task-4) No mapping found for HTTP request with URI [/resource/css/example.
css] in DispatcherServlet with name 'springDispatcher'
This is my Code:
#Order(1)
public class FrameworkBootstrap implements WebApplicationInitializer
{
private static final Logger log = LogManager.getLogger();
#Override
public void onStartup(ServletContext container) throws ServletException
{
log.info("Executing framework bootstrap.");
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(RootContextConfiguration.class);
container.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext servletContext =
new AnnotationConfigWebApplicationContext();
servletContext.register(ServletContextConfiguration.class);
ServletRegistration.Dynamic dispatcher = container.addServlet(
"springDispatcher", new DispatcherServlet(servletContext)
);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
FilterRegistration.Dynamic registration = container.addFilter(
"preSecurityLoggingFilter", new PreSecurityLoggingFilter()
);
registration.addMappingForUrlPatterns(null, false, "/*");
}
}
And the config...
#Configuration
#EnableWebMvc
#ComponentScan(
basePackages = "com.example.site",
useDefaultFilters = false,
includeFilters = #ComponentScan.Filter(Controller.class)
)
public class ServletContextConfiguration extends WebMvcConfigurerAdapter {
private static final Logger log = LogManager.getLogger();
#Inject ApplicationContext applicationContext;
#Inject ObjectMapper objectMapper;
#Inject Marshaller marshaller;
#Inject Unmarshaller unmarshaller;
#Inject SpringValidatorAdapter validator;
#Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/jsp/view/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("Adding Resource Handlers");
registry.addResourceHandler("/resource/**").addResourceLocations("/resource/");
registry.setOrder(Integer.MAX_VALUE);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters
) {
converters.add(new ByteArrayHttpMessageConverter());
converters.add(new StringHttpMessageConverter());
converters.add(new FormHttpMessageConverter());
converters.add(new SourceHttpMessageConverter<>());
MarshallingHttpMessageConverter xmlConverter
= new MarshallingHttpMessageConverter();
xmlConverter.setSupportedMediaTypes(Arrays.asList(
new MediaType("application", "xml"),
new MediaType("text", "xml")
));
xmlConverter.setMarshaller(this.marshaller);
xmlConverter.setUnmarshaller(this.unmarshaller);
converters.add(xmlConverter);
MappingJackson2HttpMessageConverter jsonConverter
= new MappingJackson2HttpMessageConverter();
jsonConverter.setSupportedMediaTypes(Arrays.asList(
new MediaType("application", "json"),
new MediaType("text", "json")
));
jsonConverter.setObjectMapper(this.objectMapper);
converters.add(jsonConverter);
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true).favorParameter(false)
.parameterName("mediaType").ignoreAcceptHeader(false)
.useJaf(false).defaultContentType(MediaType.APPLICATION_XML)
.mediaType("xml", MediaType.APPLICATION_XML)
.mediaType("json", MediaType.APPLICATION_JSON);
}
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers)
{
Sort defaultSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));
Pageable defaultPageable = new PageRequest(0, 10, defaultSort);
SortHandlerMethodArgumentResolver sortResolver =
new SortHandlerMethodArgumentResolver();
sortResolver.setSortParameter("paging.sort");
sortResolver.setFallbackSort(defaultSort);
PageableHandlerMethodArgumentResolver pageableResolver =
new PageableHandlerMethodArgumentResolver(sortResolver);
pageableResolver.setMaxPageSize(100);
pageableResolver.setOneIndexedParameters(true);
pageableResolver.setPrefix("paging.");
pageableResolver.setFallbackPageable(defaultPageable);
resolvers.add(sortResolver);
resolvers.add(pageableResolver);
}
#Override
public void addFormatters(FormatterRegistry registry)
{
if(!(registry instanceof FormattingConversionService))
{
log.warn("Unable to register Spring Data JPA converter.");
return;
}
DomainClassConverter<FormattingConversionService> converter =
new DomainClassConverter<>((FormattingConversionService)registry);
converter.setApplicationContext(this.applicationContext);
}
#Override
public Validator getValidator()
{
return this.validator;
}
#Override
public void addInterceptors(InterceptorRegistry registry)
{
super.addInterceptors(registry);
registry.addInterceptor(new LocaleChangeInterceptor());
}
#Bean
public LocaleResolver localeResolver() {
return new SessionLocaleResolver();
}
#Bean
public RequestToViewNameTranslator viewNameTranslator() {
return new DefaultRequestToViewNameTranslator();
}
}
The application is running, i'm just can't reach the files which are on the server in the following path.
src > main > webapp > resource > css > file.css
I can't find out what is wrong... Please Help!

Getting 404 status spring 4 mvc with tomcat

I am doing little project using Spring+Hibernate. When I deploy my war and get 404 status all the time. I have checked some answers about it, but I didnt find my mistake. I tried to switch between / and /*, it didnt help. Tomcat doesnt show any errors in logs. Thanks in advance.
My WebConfig class
#Configuration
#EnableWebMvc
#ComponentScan({"controller", "dao"})
#EnableTransactionManagement
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public DataSource dataSource() {
SimpleDriverDataSource ds =
new SimpleDriverDataSource(org.h2.Driver.load(), "jdbc:h2:~/testdb", "sa", "sa");
return ds;
}
#Bean
#DependsOn("dataSource")
public LocalSessionFactoryBean sessionFactoryBean() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan("entity");
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
private Properties hibernateProperties() {
Properties p = new Properties();
p.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
p.setProperty("hibernate.hbm2ddl.auto", "update");
p.setProperty("hibernate.hbm2ddl.import_files_sql_extractor", "org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor");
p.setProperty("hibernate.show_sql", "true");
p.setProperty("hibernate.format_sql", "true");
return p;
}
#Bean
#DependsOn("sessionFactoryBean")
public PlatformTransactionManager transactionManager() {
SessionFactory sessionFactory = sessionFactoryBean().getObject();
HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
return tm;
}
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
My WebAppInitializer class
public class SpringWebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}
My Controller class
#Controller
public class MainController {
#Autowired
IDisksDao d;
#RequestMapping("/")
#Transactional
#ResponseBody
public String hello() {
return "hi";
}
#RequestMapping("disks/")
#Transactional
#ResponseBody
public ModelAndView getDisks() {
ModelAndView model = new ModelAndView("disks");
model.addObject("disks", d.getAllDisks() );
return model;
}
#RequestMapping("u/disks/{id}")
#Transactional
#ResponseBody
public List<Disk> getUserDisks(#PathVariable int id) {
return d.getAllUserDisks(id);
}
}
My project structure

Spring OpenSessionInViewFilter and sessionFactory bean not found

I'm trying to add a OpenSessionInViewFilter in my Spring MVC application because accessing a collections in my Thymeleaf templates resulted in a LazyInitializationException. This is what I have:
public class ApplicationInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ApplicationContext.class);
rootContext.setDisplayName("Test");
servletContext.addListener(new ContextLoaderListener(rootContext));
ServletRegistration.Dynamic dispatcher =
servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
FilterRegistration.Dynamic filter = servletContext.addFilter("openSessionInViewFilter", OpenSessionInViewFilter.class);
filter.setInitParameter("singleSession", "true");
filter.addMappingForServletNames(null, true, "dispatcher");
}
}
And:
#Configuration
#EnableWebMvc
#ComponentScan
#Import({ SecurityConfig.class })
#PropertySource("classpath:application.properties")
#EnableJpaRepositories("test.model")
public class ApplicationContext extends WebMvcConfigurerAdapter {
#Autowired
public StringToCompany stringToCompany;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/**");
registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/**");
registry.addResourceHandler("/images/**").addResourceLocations("/resources/images/**");
}
#Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(stringToCompany);
}
#Bean
public SessionBean sessionBean() {
return new SessionBean();
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource datasource = new DriverManagerDataSource();
...
return datasource;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
LocalContainerEntityManagerFactoryBean factoryBean
= new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource( dataSource() );
factoryBean.setPackagesToScan( new String[ ] { "test.model" } );
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
factoryBean.setJpaVendorAdapter( vendorAdapter );
factoryBean.setJpaProperties( this.additionalProperties() );
return factoryBean;
}
#Bean
public PlatformTransactionManager transactionManager(){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
this.entityManagerFactory().getObject() );
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
...
return properties;
}
}
This results in
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sessionFactory' is defined
I was hoping it would be as sample as adding this:
#Bean
public AnnotationSessionFactoryBean sessionFactory() {
return new AnnotationSessionFactoryBean();
}
but that causes a while bunch of
java.lang.NoClassDefFoundError: Lorg/hibernate/cache/CacheProvider;
I finally tried changing AnnotationSessionFactoryBean to LocalSessionFactoryBean (Hibernate 4) but that gave me
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Can anyone help me integrate OpenSessionInViewFilter into my current setup? I'm trying not to use xml.
Add OpenEntityManagerInViewFilter in Spring 4
public class WebContextInitializer implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException
{
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(Application.class);
rootContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
FilterRegistration.Dynamic filter = servletContext.addFilter("openEntityManagerInViewFilter", OpenEntityManagerInViewFilter.class);
filter.setInitParameter("singleSession", "true");
filter.addMappingForServletNames(null, true, "dispatcher");
/**
* Add Spring ContextLoaderListener
*/
servletContext.addListener(new ContextLoaderListener(rootContext));
}}
Or add OpenEntityManagerInViewFilter in Spring 4 in the web.xml:
<filter>
<filter-name>openEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Categories