Two types of Aware interfaces are used in Spring to customize the acquisition of beans

Reprinted from: https://www.cnblogs.com/handsomeye/p/6277510.html

 When using spring programming, it is often encountered that you want to obtain the corresponding bean object according to the name of the bean. At this time, you can meet the requirements by implementing BeanFactoryAware. The code is very simple:

copy code
@Service
public class BeanFactoryHelper implements BeanFactoryAware { private static BeanFactory beanFactory; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } public static Object getBean(String beanName){
     if(beanFactory == null){
            throw new NullPointerException("BeanFactory is null!");
        }
     return beanFactory.getBean (beanName); 
  }
}
copy code

  Another way is to implement the ApplicationContextAware interface, and the code is also very simple:

copy code
@Service
public class ApplicationContextHelper implements ApplicationContextAware {
    
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
    
    public static Object getBean(String beanName){
        if(applicationContext == null){
            throw new NullPointerException("ApplicationContext is null!");
        }
        return applicationContext.getBean(beanName);
    }

}
copy code

  上面两种方法,只有容器启动的时候,才会把BeanFactory和ApplicationContext注入到自定义的helper类中,如果在本地junit测试的时候,如果需要根据bean的名称获取bean对象,则可以通过ClassPathXmlApplicationContext来获取一个ApplicationContext,代码如下:

copy code
  @Test
    public void test() throws SQLException {
        //通过从classpath中加载spring-mybatis.xml实现bean的获取
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-mybatis.xml");
        IUserService userService = (IUserService) context.getBean("userService");

        User user = new User();
        user.setName("test");
        user.setAge(20);
        userService.addUser(user);
    }
copy code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326493180&siteId=291194637