我有很多这样的方法:
Connection connection = null;
try {
connection = new Connection();
connection.connect();
.... // method body
} finally {
if (connection != null) {
connection.disconnect();
}
}我可以将此部分排除在apects (AspectJ)中吗?
发布于 2013-02-12 17:25:31
您可以将连接管理提取到一个周边建议中,并通过在ThreadLocal中公开上下文Connection来使业务代码可以使用它。定义一个具有静态属性的公共类:
public class ConnectionHolder {
public static final ThreadLocal<Connection> connection = new ThreadLocal<>();
}在around建议中,您必须将ThreadLocal设置为打开的连接,并且确保您在之后无条件地清除它。这是ThreadLocal最大的缺陷:将对象泄漏到不相关的上下文中。还要注意子线程继承了ThreadLocal (在WebSphere中曾经有过这样的问题)。
总而言之,Spring是一个相当糟糕的解决方案,但是任何其他的解决方案都需要你去使用像ThreadLocal这样的依赖注入框架,配置请求作用域的bean等等,这将是一个好主意,但需要你做更多的研究。
发布于 2013-02-12 14:44:31
或者,您可以使用template pattern提取连接管道,以避免复制/粘贴。基本思想是这样的:
abstract ConnectionTemplate {
private Connection connection = // ...
/**
* Method to be implementad by child classes
*/
public abstract void businessLogicCallback();
/**
* Template method that ensure that mandatory plumbing is executed
*/
public void doBusinessLogic() {
try {
openConnection();
// fetch single result, iterate across resultset, etc
businessLogicCallback();
finally {
closeConnection();
}
}
void openConnection() {
connection.open();
}
void closeConnection() {
if (connection != null) {
connection.close();
}
}
}现在,实现类可以像这样简单
class ImportantBusinessClass extends ConnectionTemplate {
@Override
public void businessLogicCallback() {
// do something important
}
}你可以像这样使用它
ImportantBusinessClass importantClass = new ImportantBusinessClass();
importantClass.doBusinessLogic(); // opens connection, execute callback and closes connectionSpring框架在某些地方使用了这种技术,特别是JdbcTemplate处理SQL、连接、行与域对象之间的映射等。有关实现细节,请参考GitHub中的source code。
https://stackoverflow.com/questions/14826396
复制相似问题