麟の随笔

  • 游戏
  • 影视
  • Tech
  1. 首页
  2. 科技
  3. Java
  4. 正文

SpringBoot工具类注入@AutoWare失败

2021年12月22日 434点热度 0人点赞 0条评论

对于非Service、Controller类,使用@Autowired注入可能会导致对象为空,故可使用ApplicationContextAware类进行注入

新增Bean类

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class Sc implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (this.applicationContext == null)
            this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

添加@Configuration配置

对于非xml配置

    @Bean(name = "Sc")
    public Sc SpringContextHolder() {
        System.err.println("初始化SC");
        return new Sc();
    }

如果要调用的类也是Bean,需要设置加载顺序,使用@DependsOn("Sc")注解保证Sc优先初始化

调用

声明要调用的对象,使用Sc.getBean方法,参数写入对象类即可

private BaseSecurityService baseSecurityService = Sc.getBean(BaseSecurityService.class);
标签: Java
最后更新:2021年12月22日

Kylin

必须有人浴血奋战,世上才有自由可言!

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2023 kirinz.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

闽ICP备19013981号