2
votes

Assume I have Spring MVC powered application with Spring security. I have:

  1. UserBean class which provides CRUD operations on table User
  2. UserController : controller which expose operation on User to http clients
  3. UserLogin: Authentication provider from Spring security, which authenticates users.

How should I configure my application if:

  1. I want simple XML configuration, with auto-discovering beans by annotations (<context:component-scan base-package="org.example"/>)
  2. UserLogin and UserController needs UserBean to work
  3. UserLogin and UserController use transaction annotations and aspect annotations

I see the following oportunities:

Create one common Spring XML configuration file, used both by DispatcherServlet and ContextLoaderListener

  • Disadvantage: nobody shows that solution in tutorial. All beans are duplicated (one instance in ContextLoaderListener context, second in DispatcherServlet). Duplication may cause some hard to track bugs. Duplication is not elegant

Create two Spring XML configuration files, one for ContextLoaderListener (main) and one for DispatcherServlet (controllers). UserBean is declared in first config and visible in second one

  • Disadvantage: to avoid duplication I have to add complex component scanning rules to both files (context:component-scan). <tx:annotation-driven and <aop:aspectj-autoproxy/> must be defined in both files. I will have still doubts which config file is appropiate when declaring new stuff.

Create two Spring XML configuration files and include third for common settings like <tx:annotation-driven

  • Disadvantage: I wanted simple solution...

Summary: I'm looking for good practice to configure application with Spring MVC + Spring Security AND security part is highly connected with business part. I was searching for good example but I always find case when security code is isolated from business code. But I need example when security and business share the code

Similar question: ContextLoaderListener or not?

2

2 Answers

2
votes

I have two xml files for my configuration, no particular reason, that's just how it worked out.

These sample spring security projects provide good examples of lots of different types of configurations maybe you can find something that works for you:

https://github.com/spring-projects/spring-security/tree/master/samples

0
votes

Hidden message in my question was: having two contexts is stupid.

  1. Did someone already notice that?
  2. Is there a way to have single application configuration?

Answers:

  1. Yes. https://jira.springsource.org/browse/SPR-6903
  2. Yes. https://github.com/michaldo/spring-single-context-demo

The best practice which applies to my case is described here: https://stackoverflow.com/a/14032213/2365727