在普通类中想要使用依赖注入 必须先对这个类创建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)
就可以获取到了!