zoukankan      html  css  js  c++  java
  • BeanNameAware和BeanFactoryAware接口

    平时写代码很少去实现这两个接口,这里只是做下了解,方便读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()));
        }

  • 相关阅读:
    初步学习“C#中is,as用法”(转载)
    SQL 语句性能调优
    算24点,给出四个数字,算出所有组合
    企业信息化实施先松后紧
    解决Json的DateTime格式问题
    Hadoop安装记录
    Test Blog by using windows live writer
    EL表达式获取对象属性的原理
    spring配置文件中配置sessionFactory失败
    Visual Studio 使用Web Deploy 3.6发布项目
  • 原文地址:https://www.cnblogs.com/xiaozhuanfeng/p/10790695.html
Copyright © 2011-2022 走看看