我正在使用NetBeans中的Java Swing为行业开发ERP。我想记录使用log4J引发的异常!和 AOP。我做了大量的搜索,但没有得到AOP与基于Swing的应用程序的集成,因为大多数示例都是针对Web框架的工作(例如Spring)。非常感谢提前。
答案 0 :(得分:3)
我没有看到你的问题。 Swing与否,您只是使用Java类。如果可以将AspectJ应用于其他Java类,则还可以将其应用于Swing类。试一试,一旦理解了基本概念,使用AspectJ的AOP真的很有趣。如果你有一个具体的问题,如果可以的话,我很乐意提供帮助。
更新:好的,我只是花了一些时间,并使用了一些sample code来为您快速演示。
最小Swing示例抛出两个RuntimeExceptions,一个在创建主窗口期间抛出,另一个在弹出对话框中单击“确定”时抛出:
import java.awt.event.*;
import javax.swing.*;
public final class MinimalSwingApplication {
public static void main(String... aArgs) {
MinimalSwingApplication app = new MinimalSwingApplication();
app.buildAndDisplayGui();
}
private void buildAndDisplayGui() {
JFrame frame = new JFrame("Main window");
buildContent(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void buildContent(JFrame aFrame) {
JPanel panel = new JPanel();
panel.add(new JLabel("Hello"));
JButton ok = new JButton("Show pop-up dialog");
ok.addActionListener(new ShowDialog(aFrame));
panel.add(ok);
aFrame.getContentPane().add(panel);
throw new RuntimeException("Oops!");
}
private static final class ShowDialog implements ActionListener {
private JFrame fFrame;
ShowDialog(JFrame aFrame) {
fFrame = aFrame;
}
public void actionPerformed(ActionEvent aEvent) {
JOptionPane.showMessageDialog(fFrame, "I am the a pop-up dialog");
throw new RuntimeException("Something unexpected happened here");
}
}
}
记录异常的示例方面(使用JDK日志记录,但您可以轻松切换到Log4J):
import java.util.logging.*;
public aspect SwingExceptionLogger {
static Logger logger = Logger.getLogger(SwingExceptionLogger.class.getName());
Object around() : execution(* MinimalSwingApplication..*(..)) {
try {
return proceed();
} catch (Exception e) {
logger.log(Level.WARNING, "Swing exception: " + e.getMessage());
return null;
}
}
}
用于启动应用程序和打开/关闭弹出对话框两次的示例输出:
10.11.2012 09:42:28 MinimalSwingApplication buildContent_aroundBody5$advice
WARNUNG: Swing exception: Oops!
10.11.2012 09:42:33 MinimalSwingApplication$ShowDialog actionPerformed_aroundBody1$advice
WARNUNG: Swing exception: Something unexpected happened here
10.11.2012 09:42:37 MinimalSwingApplication$ShowDialog actionPerformed_aroundBody1$advice
WARNUNG: Swing exception: Something unexpected happened here
如果这是您想要的,您可以始终优化切入点以仅记录AWT / Swing线程中的内容。您也可以重新抛出异常而不是吞咽异常。随意尝试或询问。