spring-boot 在普通类中无法使用@Autowired注入Service和配置文件中的值

在普通类中想要使用依赖注入 必须先对这个类创建bean

如果只是想获取配置文件得值 可以直接读取配置文件

Properties properties = PropertiesLoaderUtils.loadAllProperties("application-dev.yml");
           String capturePhoto = properties.getProperty("capturePhoto");

也可以在类上加@Component注解即可

想要获取配置文件的值,直接使用@Value 一直获取为Null

//声明静态变量值
private static String a;

@Value("${a}")
public void setA(String a) {
    this.a = a;
}

配置文件:

a: 123

这样在项目运行是 就可以获取配置文件中的值

而Service的注入也可以依靠set方法注入

//首先声明静态的service
private static CityService cityService;

@Resource
 CityService cityService1;
@PostConstruct //初始化函数手工注入
 public void init() {
     this.cityService = cityService1;
 }
 //OR  set方法注入
 @Autowired
 public void setCity(CityService cityService) {
    this.cityService = cityService;
}

// OR  构造方法注入
@Autowired
public Interception(CityService cityService)
{
    Interception.cityService=cityService;
}

还可以使用获取bean来实现

首先 手动创建一个工具类 SpringContextUtils

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

@Component
public class SpringContextUtils implements ApplicationContextAware {
    public static ApplicationContext applicationContext;

    public SpringContextUtils() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

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

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

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

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name) {
        return applicationContext.isSingleton(name);
    }

    public static Class<? extends Object> getType(String name) {
        return applicationContext.getType(name);
    }
}

然后就可以通过调用

SpringContextUtils.getBean(xxx)

就可以获取到了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值