zoukankan      html  css  js  c++  java
  • 如何在未加注解的类或类的静态方法中引用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。

  • 相关阅读:
    IIS安装和使用(Windows Server 2003)
    五险一金
    CKEditor与CKFinder的配置(ASP.NET环境)
    spring的@ConditionalOnMissingBean注解
    spring的@Primary注解
    java8实现接口需要重写接口中的default方法吗
    消息队列的作用
    ES快速入门,ElasticSearch 搜索引擎
    spring的@PostConstruct 和 @PreDestroy 注解
    Spring注解@Component、@Repository、@Service、@Controller区别
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13302502.html
Copyright © 2011-2022 走看看