我很想知道是否有一个接口可以告诉Spring启动一个特定的bean,调用它的初始化过程(通过afterPropertiesSet()作为InitializingBean,或者通过init方法,或者其他方式),然后扔掉它.
我的用例是一个简单的"健全检查器",它将在启动Web应用程序时检查数据库中的有效值.虽然我们的特定bean的开销很小,但在应用程序上下文中保持bean永远是没有意义的,因为一旦bean初始化,就不再需要了.
我确定这种行为还有其他用例,但我还没有在Spring中找到这样的东西.
特别是,我在Spring的Java变体中寻找它,我可以根据需要访问3.x及以上版本.
编辑:根据接受的答案,以下是一个简单的黑客提供解决方案:
public final class NullReturningBeanPostProcessor implements BeanPostProcessor {
private List<String> beanNamesToDiscard = new ArrayList<String>();
/**
* Creates a new {@link NullReturningBeanPostProcessor} instance.
*/
public NullReturningBeanPostProcessor() {
super();
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanNamesToDiscard.contains(beanName)) {
return null;
}
return bean;
}
public void setBeanNamesToDiscard(List<String> beanNamesToDiscard) {
if (beanNamesToDiscard != null) {
this.beanNamesToDiscard = beanNamesToDiscard;
}
}
}
Run Code Online (Sandbox Code Playgroud)
将此bean后处理器与适当的bean放在应用程序上下文中将使它们为空,并且在初始化之后有资格进行垃圾回收.遗憾的是,bean配置元数据仍将保留在应用程序上下文中.
我想知道是否有办法将ArrayList(或任何类型的List)绑定到PreparedStatement,最终将用于访问Oracle数据库.我发现:
这看起来与我的问题类似,但这个问题更具体:我想将一个ArrayList绑定到要在Oracle中使用的PreparedStatement,如果可能的话,这是如何实现的?
问题是听起来 - 如何根据浏览器输入检索客户端用户的时区?如果重要的话,使用服务器端J2EE,但我不认为在这种情况下真的很重要.现在,HTTP是协议,它可以在它上线时使用HTTPS.
Javamail是异步还是同步?也就是说,如果我发送电子邮件,我会在之后立即继续处理,还是等到它完成?
此外,有什么方法我可以抓住电子邮件因任何原因未能送达?
我也想知道Spring的MailSender抽象的这些答案.
谢谢.
我当前的构建主管在理论上有一个好主意 - 构建一个自定义Log4J appender,它接受Spring管理的bean并使用它们将错误记录到除标准日志文件之外的各种其他源.但是,除了创建一个在启动时使用应用程序上下文(代码片刻)初始化的单例之外,我似乎无法想到在Log4J appender中检索Spring托管bean的任何其他选项.
public class SpringSingleton implements ApplicationContextAware {
private static ApplicationContext context;
public SpringSingleton() {
super();
}
public static ApplicationContext getContext() {
return SpringSingleton.context;
}
public void setApplicationContext(ApplicationContext context) {
if(SpringSingleton.context != null) {
throw new IllegalStateException("Context is already set!");
}
SpringSingleton.context = context;
}
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,这些属性可以像Spring中的bean一样通过依赖注入设置 - 无论初始化多少个appender,bean引用都不会改变.有任何想法吗?
我使用Maven(2)Cobertura插件创建代码覆盖率报告,我在方法中使用以下存根:
try {
System.exit(0);
} catch (final SecurityException exception) {
exception.printStackTrace();
}
System.err.println("The program never exited!");
Run Code Online (Sandbox Code Playgroud)
我知道我需要记录异常等,但现在不是重点...... Cobertura拒绝承认打印堆栈跟踪后的行被覆盖.也就是说,System.err.println语句前面带有'}'的行没有显示为覆盖.之前,该方法的结束大括号未显示为覆盖,因此System.err声明.任何想法如何说服cobertura的maven插件,因为System.err.println声明被覆盖,结束括号必须被覆盖?
哦是的,我使用模拟安全管理器抛出安全异常,因为这是我发现在System.exit调用后继续执行测试的最简单方法.