问题
I am trying to add Spring Security - OAuth2 to my Rest API which resides on embedded Jetty. I am getting "No bean named 'springSecurityFilterChain' is defined" error. When I add a ContextLoadListener with
context.addEventListener( new ContextLoaderListener() );
I start getting
Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!"
error. The following is the structure of my Code
public class Launcher
{
public static void main( String[] args )
{
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext( CMApplicationConfig.class, TestConfig.class);
JettyServer server = new JettyServer();
server.start( ctx );
}
}
public class JettyServer
public void start( AnnotationConfigApplicationContext c )
{
ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS );
// Set application context parent of webapp context. The purpose is sharing singleton objects which reside on the application side with Jetty context
final GenericWebApplicationContext webApplicationContext = new GenericWebApplicationContext();
webApplicationContext.setServletContext(context.getServletContext());
webApplicationContext.setParent(c);
webApplicationContext.refresh();
context.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
context.setContextPath( "/" );
ServletHolder springServlet = context.addServlet( org.springframework.web.servlet.DispatcherServlet.class, "/" );
springServlet.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
springServlet.setInitParameter( "contextConfigLocation", "config.CMWebContextConfiguration");
springServlet.setInitOrder( 1 );
// Add spring security
context.addFilter(new FilterHolder( new DelegatingFilterProxy( "springSecurityFilterChain" ) ),"/*", EnumSet.allOf( DispatcherType.class ));
//This gives: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader
context.addEventListener( new ContextLoaderListener() );
// Configure server
_jettyServer = new Server( createThreadPool() );
_jettyServer.setConnectors( createConnectors( _jettyServer ) );
_jettyServer.setHandler( context );
try
{
_jettyServer.start();
}
catch ( Exception ex )
{
ex.printStackTrace();
}
}
来源:https://stackoverflow.com/questions/29365858/adding-spring-security-to-embedded-jetty