平时写代码很少去实现这两个接口,这里只是做下了解,方便读Spring源码。
BeanNameAware接口作用:让Bean对Name或id有知觉
package com.example.demo.biz.service; import org.springframework.beans.factory.BeanNameAware;
import org.springframework.stereotype.Service; /**
* BeanNameAware作用:让Bean对Name有知觉
*/
@Service
public class BizService implements BeanNameAware {
private String beanName; @Override
public void setBeanName(String s) {
this.beanName = s;
} public String getBeanName() {
return beanName;
}
}
测试
package com.example.demo.biz.service; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; @RunWith(SpringRunner.class)
@SpringBootTest
public class BeanNameAwareTest { @Resource
private BizService bizService; @Test
public void test1(){
System.out.println(bizService.getBeanName());
}
}
结果:
BeanFactoryAware接口:让Bean获取配置他们的BeanFactory的引用。
修改下上面的例子
package com.example.demo.biz.service; import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.stereotype.Service; /**
* BeanNameAware作用:让Bean对Name有知觉
*/
@Service
public class BizService implements BeanNameAware, BeanFactoryAware {
private String beanName; private BeanFactory factory; @Override
public void setBeanName(String s) {
this.beanName = s;
} public String getBeanName() {
return beanName;
} @Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.factory = beanFactory;
} public BeanFactory getFactory() {
return factory;
} @Override
public String toString() {
return "----------------------->";
}
}
@Test
public void test2(){
System.out.println(bizService.getFactory().getBean(bizService.getBeanName()));
}