一、前言
通过实现springframework的spring-bean源码包中org.springframework.beans.factory.BeanNameAware接口,可以获取打印注册到bean工厂类的bean对象id,详情参见代码示例。
二、代码示例
1.MyDefinedNamedBean的BeanNameAware接口实现类
package com.test;@b@@b@import org.springframework.beans.factory.BeanNameAware;@b@import org.springframework.stereotype.Service;@b@@b@@Service@b@public class MyDefinedNamedBean implements BeanNameAware {@b@@b@ private String beanName = null;@b@@b@ public void setBeanName(String beanName) {@b@ this.beanName = beanName;@b@ System.out.println("回调setBeanName方法 id属性是"+beanName);@b@ }@b@@b@ @b@ @Override@b@ public String toString() {@b@ return "MyDefinedNamedBean@beanName:mybean@"+this.hashCode();@b@ }@b@@b@}
2. junit测试类(完整的项目工程测试代码参见其他文章页)
package com.test;@b@@b@import org.junit.Test;@b@import org.springframework.beans.factory.annotation.Autowired;@b@import org.springframework.test.context.ContextConfiguration;@b@import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;@b@@b@@ContextConfiguration(locations={"classpath*:springContext.xml"})@b@public class TestBase extends AbstractJUnit4SpringContextTests { @b@ @b@ @Autowired@b@ public MyDefinedNamedBean myDefinedNamedBean;@b@ @b@ @Test@b@ public void testBean(){ @b@ myDefinedNamedBean.toString();@b@ }@b@@b@}
运行结果如下
.....@b@回调setBeanName方法 id属性是myDefinedNamedBean