import org.springframework.beans.factory.BeanNameAware;
public class NamedSinger implements BeanNameAware {
private String name;
/** @Implements {@link BeanNameAware#setBeanName(String)} */
public void setBeanName(String beanName) {
this.name = beanName;
}
public void sing() {
System.out.println("Singer " + name + " - sing()");
}
}
获取当前Bean名称
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.GenericApplicationContext;
public class ShutdownHookBean implements ApplicationContextAware {
private ApplicationContext ctx;
/** @Implements {@link ApplicationContextAware#s
etApplicationContext(ApplicationContext)} }*/
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
if (ctx instanceof GenericApplicationContext) {
((GenericApplicationContext) ctx).registerShutdownHook();
}
}
}
和获取当前Bean的ApplicationContext
本文探讨了在Spring框架中如何实现BeanNameAware接口来获取当前Bean的名称,以及通过ApplicationContextAware接口获取当前Bean的ApplicationContext上下文。示例代码展示了具体实现方式。
3779

被折叠的 条评论
为什么被折叠?



