HTTP Status 404 - Using Spring+Tomcat - spring

I am beginner to Spring and I am working on my learning project. With below code, I can view the index.jsp but not test.jsp. I use Spring 4.0.1+ Tomcat 7.0.52 + STS 3.4.0.
Webapp.java
package springweb;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class Webapp extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[0];
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{ WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[]{ "/" };
}
}
IndexController.java
package springweb.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class IndexController {
private static final Logger logger = LoggerFactory.getLogger(IndexController.class);
#RequestMapping(value="/")
public String index() {
logger.info("Welcome Index!");
return "index";
}
}
TestController.java
package springweb.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class TestController {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
#RequestMapping(value="/test/", method = RequestMethod.GET)
public String test() {
logger.info("Welcome test!");
return "test";
}
}
WebConfig.java
package springweb;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages={"springweb.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

Simple answer for 100% free xml:
Set property for the DispatcherServlet
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {AppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
//that's important!!
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
boolean done = registration.setInitParameter("throwExceptionIfNoHandlerFound", "true"); // -> true
if(!done) throw new RuntimeException();
}
}
Create #ControllerAdvice:
#ControllerAdvice
public class AdviceController {
#ExceptionHandler(NoHandlerFoundException.class)
public String handle(Exception ex) {
return "redirect:/404";
}
#RequestMapping(value = {"/404"}, method = RequestMethod.GET)
public String NotFoudPage() {
return "404";
}
}
that's all

Related

After adding #PathVariable, resources become unreachable

#GetMapping("/instructor-edit-course")
private String instructorAddCourse(Model model) {
model.addAttribute("course", new Course());
return "instructor-edit-course";
}
Above code is ok. Resources are found.
But when I add #PathVariable to the path like below code, application searches resources in
http://localhost:8080/instructor-edit-course/assets/images/icon/footer/facebook-square#2x.png
instead of
http://localhost:8080/assets/images/icon/footer/facebook-square#2x.png
#GetMapping("/instructor-edit-course/{id}")
private String instructorEditCourse(#PathVariable String id, Model model) {
// go to course page
Course course = courseService.findById(Integer.parseInt(id));
model.addAttribute("course", course);
return "instructor-edit-course";
}
WebConfig class
package com.hrglob.elearning.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.xxxx.*"})
public class WebConfig implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**")
.addResourceLocations("/public", "classpath:/static/", "classpath:/static/assets/")
.setCachePeriod(31556926);
}
#Bean
#Description("Thymeleaf template resolver serving HTML 5")
public ClassLoaderTemplateResolver templateResolver() {
var templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("templates/");
templateResolver.setCacheable(false);
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setOrder(0);
return templateResolver;
}
#Bean
#Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
var templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
#Bean
#Description("Thymeleaf view resolver")
public ViewResolver viewResolver() {
var viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
}

404 error in Spring Maven project

I am new to Spring and trying to develop one small application using spring annotation with Maven. But I am getting **"The requested resource is not available."**I can understand that server is not able to locate the requested resource. But I am not able to resolve it, So please help me on this.
Below are my project structure and code:-
SpringRootConfig.java
package com.capp.config;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.ComponentScan;
#Configurable
#ComponentScan( basePackages = {"com.capp"})
public class SpringRootConfig {
}
package com.capp.config;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#SuppressWarnings("deprecation")
#Configurable
#ComponentScan( basePackages = {"com.capp"})
#EnableWebMvc
public class SpringWebConfig extends WebMvcConfigurerAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver vr =new InternalResourceViewResolver();
vr.setViewClass(JstlView.class);
vr.setPrefix("/WEB-INF/view/");
vr.setSuffix(".jsp");
return vr;
}
}
ContactAppDispatcherServletIntializer.java
package com.capp.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ContactAppDispatcherServletIntializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {SpringRootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class[] {SpringRootConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/"};
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
// TODO Auto-generated method stub
super.onStartup(servletContext);
}
}
TestController.java
package com.capp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class TestController {
#RequestMapping(value="/test/hello")
public String helloWorld() {
return "hello";
}
}
When i am runing the application with http://localhost:8080/SpringContactApp/test/hello not able to find the hello.jsp which is under WEB-INF folder.
I presume the JSP is directly under the WEB-INF folder. If this is the case, create a subdirectory 'view' and move the JSP there.
In the view resolver, you set the prefix to "/WEB-INF/view/", your view resources must be in that location.

limit login attempts using applicationlistener spring security 4 annotation based

I have used application listener foe limiting login attempts but not able to get where to register this application listener as my project is full annotation based with no xml
Athentication Listener
#Component
public class AuthenticationListener implements ApplicationListener <AbstractAuthenticationEvent>
{
#Override
public void onApplicationEvent(AbstractAuthenticationEvent appEvent)
{
System.out.println("got in authentication here");
if (appEvent instanceof AuthenticationSuccessEvent)
{
AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
// add code here to handle successful login event
System.out.println("THERE WAS A SUCCESSFUL LOGIN");
}
if (appEvent instanceof AuthenticationFailureBadCredentialsEvent)
{
AuthenticationFailureBadCredentialsEvent event = (AuthenticationFailureBadCredentialsEvent) appEvent;
// add code here to handle unsuccessful login event
// for example, counting the number of login failure attempts and storing it in db
// this count can be used to lock or disable any user account as per business requirements
System.out.println("THERE WAS A UNSUCCESSFUL LOGIN");
}
}
}
SpringSecurity
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
#Configuration
#EnableWebSecurity
//#EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurity extends WebSecurityConfigurerAdapter {
// #Autowired
// #Qualifier("authenticationProvider")
// static AuthenticationProvider authenticationProvider;
//
// #Autowired
// public static void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// auth.authenticationProvider(authenticationProvider);
// }
#Override
protected void configure(HttpSecurity http) throws Exception {
try{
System.out.println("----TOP--------Http Security");
http
//.httpBasic()
//.and()
//.sessionCreationPolicy(SessionCreationPolicy.NEVER)
//.and()
.authorizeRequests()
//.antMatchers(HttpMethod.GET,"/employees").access("hasRole('ROLE_idAdmin') or hasRole('ROLE_dAdmin')")
.antMatchers(HttpMethod.GET,"/employees/?*").access("hasRole('ROLE_technician') or hasRole('ROLE_DADMIN') or hasRole('ROLE_IDADMIN') or hasRole('ROLE_WADMIN')")
//.antMatchers(HttpMethod.POST,"/employees").access("hasRole('ROLE_IDADMIN') or hasRole('ROLE_DADMIN')")
.and()
.formLogin()
//.antMatchers(HttpMethod.PUT,"/employees").access("hasRole('ROLE_IDADMIN') or hasRole('ROLE_DRADMIN') or hasRole('ROLE_WADMIN')")
//.antMatchers(HttpMethod.DELETE,"/employees").access("hasRole('ROLE_IDADMIN')")
//.antMatchers("/main").access("hasRole('ROLE_SUPERADMIN')")
//.antMatchers("/confidential/**").access("hasRole('ROLE_SUPERADMIN')")
// .exceptionHandling().accessDeniedPage("/index.jsp")
// .and()
// .httpBasic();
//.and()
//.logout()
//.permitAll();
;
System.out.println("----Bottom--------Http Security");
//.logout();
//getConnection();
//http.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class);
http.csrf().disable();
}
catch(Exception e){
System.out.println("http Security error");
e.printStackTrace();
}
}
#Configuration
protected static class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
// #Autowired
// //#Qualifier("authenticationProvider")
// static AuthenticationProvider authenticationProvider;
#Override
//#Autowired//custom addition
public void init(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("1111111111111111Authentication Manager Got here1111111");
auth
.ldapAuthentication()
.userSearchFilter("uid={0}")
.userSearchBase("ou=users")
.groupSearchFilter("uniqueMember={0}")
.groupSearchBase("ou=groups")
.groupRoleAttribute("cn")
.rolePrefix("ROLE_")
.contextSource(getLdapContextSource());
//auth.authenticationProvider(authenticationProvider);
System.out.println("Authentication Manager Got here");
}
private LdapContextSource getLdapContextSource() throws Exception {
LdapContextSource cs = new LdapContextSource();
cs.setUrl("ldap://localhost:1389/");
cs.setBase("o=id workshop");
cs.setUserDn("uid=admin,ou=system");
cs.setPassword("secret");
cs.afterPropertiesSet();
return cs;
}
}
}
AppInitializer
import javax.servlet.ServletContext;
import org.springframework.context.ApplicationListener;
//import org.krams.tutorial.controller.Equivalentwebxml;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.authenticationattempt.AuthenticationListener;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { EquivalentServlet.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
EquivalentServlet
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.security.SpringSecurity;
#EnableWebMvc
#Configuration
#ComponentScan({ "com.controller" })
#Import(value = { SpringSecurity.class })
//#Import(value = { AuthenticationListener.class})
public class EquivalentServlet {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

Spring 4 Async not working

I am working on a Spring 4 web application and have run into a problem with #Async running synchronously. This is 100% annotation driven. No XML files.
App:
package com.kc2112.app;
import com.kc2112.app.controllers.MyStopWatch;
import javax.annotation.Resource;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#EnableAsync
#EnableScheduling
#Configuration
public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer implements AsyncConfigurer {
#Resource
#Qualifier("stopwatch")
public MyStopWatch stopwatch;
public WebApp() {
super();
stopwatch = new MyStopWatch();
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[0];
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{AppConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
public TaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
te.setMaxPoolSize(25);
te.setThreadNamePrefix("LULExecutor-");
te.initialize();
return te;
}
#Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}
Configuration:
package com.kc2112.app;
import com.kc2112.app.controllers.MySampleService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration
#EnableAsync
#ComponentScan( basePackages = {"com"}, excludeFilters={
#ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=MySampleService.class)} )
public class AppConfig{
#Bean
public static PropertySourcesPlaceholderConfigurer properties() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public UrlBasedViewResolver urlBasedViewResolver()
{
UrlBasedViewResolver res = new InternalResourceViewResolver();
res.setViewClass(JstlView.class);
res.setPrefix("/WEB-INF/jsp/");
res.setSuffix(".jsp");
return res;
}
}
Controller:
package com.kc2112.app.controllers;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class MyAsyncController {
#Autowired
MyStopWatch stopwatch;
public MySampleService mySampleService = new MySampleService();
#RequestMapping(value = "/go", produces = {MediaType.TEXT_HTML_VALUE}, method = RequestMethod.GET)
public String taskExecutor() throws InterruptedException, ExecutionException {
ArrayList<Future<Boolean>> asyncResults = new ArrayList();
for (int i = 0; i < 10; i++) {
asyncResults.add(mySampleService.callAsync(i));
}
return "time passed is " + stopwatch.getTime();
}
}
Component:
package com.kc2112.app.controllers;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
#Component
public class MySampleService {
#Async
public Future<Boolean> callAsync(int taskCall) throws InterruptedException {
System.out.println("starting thread" + taskCall);
for (int i = 0; i < 10; i++) {
System.out.println("thread " + taskCall + " count is " + i);
}
return new AsyncResult<Boolean>(true);
}
}
Stopwatch:
package com.kc2112.app.controllers;
import org.apache.commons.lang.time.StopWatch;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
#Component
#Service
#Qualifier("stopwatch")
public class MyStopWatch extends StopWatch {
public MyStopWatch(){
super();
this.start();
}
}
I've tried a multitude of things, but it always prints results which are obviously not async.
public MySampleService mySampleService = new MySampleService();
This is the cause of your troubles. You must autowire the MySampleService into your controller instead of creating an instance yourself. That's the only way for Spring to wrap the component into an async proxy that will detect the annotation, intercept the method call, create a task and submit it to an executor.
YES!!!! After reading through this post:
Spring ThreadPoolTaskExecutor only running one thread
I made a few changes to my app class. The critical issue appears to be to set the core pool size. Here is the class with the line that fixed the issue...
Here's the spring docs on it:
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/scheduling/concurrent/ThreadPoolTaskExecutor.html#setCorePoolSize-int-
package com.kc2112.app;
import com.kc2112.app.controllers.MyStopWatch;
import javax.annotation.Resource;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#EnableAsync
#EnableScheduling
#Configuration
public class WebApp extends AbstractAnnotationConfigDispatcherServletInitializer implements AsyncConfigurer {
#Resource
#Qualifier("stopwatch")
public MyStopWatch stopwatch;
public WebApp() {
super();
stopwatch = new MyStopWatch();
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[0];
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{AppConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
public TaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor te = new ThreadPoolTaskExecutor();
te.setMaxPoolSize(25);
te.setThreadNamePrefix("LULExecutor-");
te.setCorePoolSize(25); //This was the critical line...
te.initialize();
return te;
}
#Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return null;
}
}

Spring: #Autowired for POJO, that not managed by Spring [duplicate]

This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 8 years ago.
i use the #Autowired to inject some services in the POJOs. The servieces are registred as Beans.
If once POJO is managed by Spring (it is registred as Bean on Spring Config too), so i have no problem with injected services.
But if i created "classic" POJO and create it by "new" , so no Services will be injected.
My question: is it possible to configurate Spring, to realize the #Autowired injection?
I use the Spring 4.0.3 that is configured by JavaConfig:
====
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.accept.ContentNegotiationManagerFactoryBean;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import com.tr.oauth.service.PhotoInfo;
import com.tr.oauth.service.PhotoService;
import com.tr.oauth.service.impl.PhotoServiceImpl;
import com.tr.oauth.service.oauth.ExtendedApprovalStoreUserApprovalHandler;
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public ContentNegotiatingViewResolver contentViewResolver() throws Exception {
ContentNegotiationManagerFactoryBean contentNegotiationManager = new ContentNegotiationManagerFactoryBean();
contentNegotiationManager.addMediaType("json", MediaType.APPLICATION_JSON);
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
MappingJackson2JsonView defaultView = new MappingJackson2JsonView();
defaultView.setExtractValueFromSingleKeyModel(true);
ContentNegotiatingViewResolver contentViewResolver = new ContentNegotiatingViewResolver();
contentViewResolver.setContentNegotiationManager(contentNegotiationManager.getObject());
contentViewResolver.setViewResolvers(Arrays.<ViewResolver>asList(viewResolver));
contentViewResolver.setDefaultViews(Arrays.<View>asList(defaultView));
return contentViewResolver;
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
#Bean
public PhotoServiceUserController photoServiceUserController(PhotoService photoService) {
PhotoServiceUserController photoServiceUserController = new PhotoServiceUserController();
return photoServiceUserController;
}
#Bean
public PhotoController photoController(PhotoService photoService) {
PhotoController photoController = new PhotoController();
photoController.setPhotoService(photoService);
return photoController;
}
#Bean
public AccessConfirmationController accessConfirmationController(ClientDetailsService clientDetailsService, ApprovalStore approvalStore) {
AccessConfirmationController accessConfirmationController = new AccessConfirmationController();
accessConfirmationController.setClientDetailsService(clientDetailsService);
accessConfirmationController.setApprovalStore(approvalStore);
return accessConfirmationController;
}
#Bean
public PhotoServiceImpl photoServices() {
List<PhotoInfo> photos = new ArrayList<PhotoInfo>();
photos.add(createPhoto("1", "marissa"));
photos.add(createPhoto("2", "paul"));
photos.add(createPhoto("3", "marissa"));
photos.add(createPhoto("4", "paul"));
photos.add(createPhoto("5", "marissa"));
photos.add(createPhoto("6", "paul"));
PhotoServiceImpl photoServices = new PhotoServiceImpl();
photoServices.setPhotos(photos);
return photoServices;
}
#Bean
public AdminController adminController(TokenStore tokenStore, ConsumerTokenServices tokenServices,
ExtendedApprovalStoreUserApprovalHandler userApprovalHandler) {
AdminController adminController = new AdminController();
adminController.setTokenStore(tokenStore);
adminController.setTokenServices(tokenServices);
adminController.setUserApprovalHandler(userApprovalHandler);
return adminController;
}
private PhotoInfo createPhoto(String id, String userId) {
PhotoInfo photo = new PhotoInfo();
photo.setId(id);
photo.setName("photo" + id + ".jpg");
photo.setUserId(userId);
photo.setResourceURL("/impl/resources/" + photo.getName());
return photo;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
-----------
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
/**
* #author Dave Syer
*
*/
public class ServletInitializer extends AbstractDispatcherServletInitializer {
#Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.scan(ClassUtils.getPackageName(getClass()));
return context;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
DelegatingFilterProxy filter = new DelegatingFilterProxy("springSecurityFilterChain");
filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
servletContext.addFilter("springSecurityFilterChain", filter).addMappingForUrlPatterns(null, false, "/*");
}
}
Yes this is possible with the #Configurable annotation and some byte-code magic.
Oliver Gierke the guy behind Spring Data created a nice blog post on this topic:
http://olivergierke.de/2009/05/using-springs-configurable-in-three-easy-steps/
http://aredko.blogspot.de/2011/02/using-configurable-in-spring-framework.html
There is also a question with no accepted answer on SO:
Spring autowiring using #Configurable

Resources