AspectJ in Scala Example

Is there a working example, including the configurations required, available of a project working with Scala and AspectJ please ?

Thanks :slight_smile:

Gianluca - that might be a very rare thing.

In Scala we’ll frequently build our own higher-order functions to cover a lot of the use cases for AspectJ. It’s very easy - for example - to write a “whenever I use a database” higher-order function to put general database pre- and post- operations in.

This approach would leave out one of AspectJ’s main use cases: injecting code at point cuts in someone else’s library.

Theoretically using AspectJ should work reasonably well on Scala byte code. I’ve never seen an example.

We use AspectJ with Scala all the time. You must use load-time weaving, but it works the same as with Java.

2 Likes

Thanks a lot for your help.

Could you kindly provide me with an example project maybe that would highlight the main principles and how to execute it please ?

Thanks a lot and good day :slight_smile:

I don’t have an example-project, but really - any example-project in Java will do as long as LTW is concerned, as LTW loads class-files and does the instrumentation at runtime (class load time). There are many examples using Spring and AspectJ, note that you need -javaagent:path/to/spring-instrument.jar for LTW to work.

1 Like

Thanks a lot for your help :slight_smile: I’ll try it out :slight_smile: So what I need is only to work like in Java, but instead address the Main Class as for example Main.scala right ?

Thanks a lot and good day :slight_smile:

There’s nothing AspectJ-specific about running a program written in Scala vs. Java, as LTW operates on class-files at runtime. If you have any concrete problems it’s best to post the details here.

I have these classes (copied them from a book “AspectJ in Action Second Edition” :

SecurityAspect.aj

//Listing 2.3 Aspect to secure access
public aspect SecurityAspect {
	private Authenticator authenticator = new Authenticator();

	pointcut secureAccess() : execution(* MessageCommunicator.deliver(..));

	before() : secureAccess() {
		System.out.println("Checking and authenticating user");
		authenticator.authenticate();
	}
}

Main.java

public class Main {
	public static void main(String[] args) {
		MessageCommunicator messageCommunicator = new MessageCommunicator();
		messageCommunicator.deliver("Wanna learn AspectJ?");
		messageCommunicator.deliver("Harry", "having fun?");
	}
}

MessageCommunicator.java

public class MessageCommunicator {
	public void deliver(String message) {
		System.out.println(message);
	}

	public void deliver(String person, String message) {
		System.out.println(person + ", " + message);
	}
}

Authenticator.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Authenticator {
	private ThreadLocal<String> authenticatedUser = new ThreadLocal<String>();
	
	public void authenticate() {
		if (isAuthenticated()) {
			return;
		}
		String[] userNamePassword = getUserNamePassword();
		if (!userNamePassword[0].equals(userNamePassword[1])) {
			throw new AuthenticationException("User/password didn't match");
		}
		authenticatedUser.set(userNamePassword[0]);
	}
	
	public boolean isAuthenticated() {
		return authenticatedUser.get() != null;
	}
	
	public String[] getUserNamePassword() {
		boolean usePrintln = Boolean.getBoolean("ant.run");
		String[] userNamePassword = new String[2];
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		try {
			if (usePrintln) {
				System.out.println("Username: ");
			} else {
				System.out.print("Username: ");
			}
			userNamePassword[0] = in.readLine().trim();
			if (usePrintln) {
				System.out.println("Password: ");
			} else {
				System.out.print("Password: ");
			}
			userNamePassword[1] = in.readLine().trim();
		} catch (IOException ex) {
			// ignore... will return array of null strings
		}
		return userNamePassword;
	}

}

AuthenticatorException.java

public class MessageCommunicator {
	public void deliver(String message) {
		System.out.println(message);
	}

	public void deliver(String person, String message) {
		System.out.println(person + ", " + message);
      }
}

Now I am trying to use aspectj :

Compiling Commands :

ajc -source 5 *.java *.aj
java (-cp path where Main is) Main

However this error crops up :

Exception in thread "main" java.lang.NoClassDefFoundError: org/aspectj/lang/NoAspectBoundException
        at MessageCommunicator.deliver(MessageCommunicator.java:20)
        at Main.main(Main.java:21)
Caused by: java.lang.ClassNotFoundException: org.aspectj.lang.NoAspectBoundException
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
        ... 2 more

Could anybody help please ?

Thanks a lot and good day :slight_smile:

Not to be rude, but; I suggest you ask AspectJ-specific questions on some AspectJ-forum/mailing-list.

Thanks a lot everyone :slight_smile: