0

I'm using spring to build Controller -> Service -> Repository architecture.

However, others developer can autowired repository in controller or anywhere.

I don't want others to violate the 3 layer architecture.

So, I using aspectj to check caller for Repository.

if caller is Service -> pass;

else throw exception.

@Aspect
public class ModelAdvice {
    private Pattern pattern = Pattern.compile("^demo\\.services\\..*");

    @Before("execution(* demo.repositories..*Repository.*(..))")
    public void protectRepositories(JoinPoint joinPoint) {
        StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
        for (StackTraceElement element : stElements) {
            Matcher matcher = pattern.matcher(element.getClassName());
            if (matcher.matches()) {
                return;
            }
        }
        throw new RuntimeException("security violation!");
    }
}

It work, but ugly and may be slow.

Is spring have some elegant way to do this?

user1094988
  • 1
  • 1
  • 2
  • 1
    Hide your repository, make them package protected and put them next to your services. Take a look here http://www.olivergierke.de/2013/01/whoops-where-did-my-architecture-go/. So it isn't so much a matter of preventing people from doing it, but making it impossible al together by having a good architecture. – M. Deinum Apr 30 '14 at 06:49
  • I think this is more a code review problem, have you tried using something like SonarQube, it has a feature called Architecture Rule Engine, which might help you achieve what you need. http://docs.codehaus.org/display/SONAR/Architecture+Rule+Engine – Sudarshan Apr 30 '14 at 06:54
  • If suggested SonarQube is too heavy, you can setup checkstyle with import control rule that prevents certain imports into certain packages to enforce architecture. You can specify that class from repository package may not be imported into classes in web/controller package. http://stackoverflow.com/questions/16142898/checkstyle-rule-to-limit-interactions-between-root-packages-with-importcontrol – Krešimir Nesek Apr 30 '14 at 09:04

0 Answers0