1.工具类
/** @author wangwei 上下文获取bean */
@Component
public class ApplicationContextUtils implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtils.context = applicationContext;
}
public static ApplicationContext getContext() {
return context;
}
public static Object getBean(String beanName) {
return context.getBean(beanName);
}
public static <T> T getBean(String beanName, Class<T> requiredType) {
return context.getBean(beanName, requiredType);
}
public static <T> T getBean(Class<T> requiredType) {
String simpleName = requiredType.getSimpleName();
String name = WordUtils.uncapitalize(simpleName);
T obj = null;
try {
obj = getBean(name, requiredType);
} catch (NoSuchBeanDefinitionException e) {
}
if (obj != null) {
return obj;
}
return context.getBean(requiredType);
}
}
2.使用
2.1application.yml 配置文件中有 配置项(物理文件上传地址)
2.2 上传配置 UploadConfig
@Component
@Data
@ConfigurationProperties(prefix = "upload")
public class UploadConfig {
private String rootUploadPath;
private Long maximumFileSize;
private String serverName;
public String getAvatarPath() {
return this.getRootUploadPath() + "avatar/";
}
}
2.3 实例
UploadConfig uploadConfig = ApplicationContextUtils.getBean(UploadConfig.class);