如何在未加注解的类或类的静态方法中引用Spring bean

一个未加注解的普通类是不会被Spring管理的,那么如何在这个普通类中引用Spring bean呢?

1:如果直接在普通类里面通过以下方式注入,那么在使用注入的对象时是会报空指针异常的。

原因:因为SendSMSUtil未加注解,所以其不会被加入到Spring容器中被管理,那么spring容器自然无法为其通过@Autowired注入别的对象。

2:需要从spring上下文ApplicationContext中获取其他类的对象。

@Component 
public class ApplicationContextProvider implements ApplicationContextAware { 

    private static ApplicationContext applicationContext; 
    
    @Override 
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 
         this.applicationContext = applicationContext; 
    } 
    public static ApplicationContext getApplicationContext() { 
        return applicationContext; 
    }
    public static Object getBean(String name) { 
         return this.applicationContext.getBean(name); 
    } 
    public static <T> T getBean(Class<T> tClass) { 
         return this.applicationContext.getBean(tClass); 
    } 
}

首先实现ApplicationContextAware接口,并通过注解@Component将实现类加入到spring容器中,这样以来可以通过setApplicationContext方法获取ApplicationContext对象;然后在该类中定义从ApplicationContext中获取bean的方法。

@Service 
public class TestService {  
      public void test() { 
           logger.info("进入TestService");
    } 
}

public class SendSMSUtil {  
       public void test() {
            TestService testService = ApplicationContextProvider.getBean(TestService.class); 
            testService.test(); 
       } 
}

在SendSMSUtil类中通过上图提供的获取bean的静态方法来从ApplicationContext中获取bean。

在类的静态方法中也是无法使用@Autowired注入的对象,也只能通过上述方法来使用springbean。

原文地址:https://www.cnblogs.com/hzcya1995/p/13302502.html