SpringBoot 注解@Value的使用

SpringBoot 注解@Value的使用

使用环境:系统在开发和正式运营之间的环境不相同,每一次部署服务器都需要更改相关配置,感觉比较麻烦。因为springboot框架之前已经配置了多环境运行,所以就想使用@Value这个注解,将环境变量写在配置文件中,让他根据运行的环境进行读取。期间遇到@Value的各种使用问题,就记录下来,别忘记了…

正常使用

  • yml配置文件部分
### 自己配置的参数
savePath : /Users/a/Desktop/test998/
libraryPath : /opt/local/share/OpenCV/java/libopencv_java347.dylib
  • 正常读取代码
@Service
public class TesseractOrcServiceImpl implements TesseractOrcService {

    @Value("${savePath}")
    private  String savePath ;
}

这样系统就已经可以读取到配置文件中的数据了

静态变量赋值

在处理静态变量时候,使用上面的@Value的用法是无法获取到配置文件中的数据的,只能获取到null,所以要进行如下更改。

利用IDEA生成该静态变量的set方法,然后删除该方法的static修饰然后将注解@Value写在set函数上面,这样就可以正常读取到配置文件中的信息。

@Service
public class TesseractOrcServiceImpl implements TesseractOrcService {

    private static String savePath ;

    @Value("${savePath}")
    public void setSavePath(String savePath) {
        TesseractOrcServiceImpl.savePath = savePath;
    }
    
    @Override
    public ResultBean ScanVinForTesseractOrc(String url) {
        String str = null;
        try {
            if(!FileUtil.exist(savePath)){
                FileUtil.mkdir(savePath);
            }
        } catch (Exception e) {
            String errerMsg=ExceptionUtil.stacktraceToString(e);
            logger.error(errerMsg);
        }
        return null;
    }
}

我对这串代码进行了debug

 @Value("${savePath}")
    public void setSavePath(String savePath) {
        TesseractOrcServiceImpl.savePath = savePath;
    }

他执行的非常早,在系统尚未正式启动之前就已经执行了,应该是在spring初始化bean内容时执行的

静态代码块中赋值使用

在我的系统中,我又一个工具类需要加载系统的静态资源库
所以要在工具类的静态代码块中获取配置文件中的属性,我使用上面那种方法,发现读取到的依然是null.

因为静态代码块是在spring操作之前执行,所以是获取不到数据的。

参考博客测试了一下,发现真是个不错的想法

ApplicationContextHolder.java 源码

package hai.guo.novel.config;

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

/**
 * @program: novel
 * @description: Redis缓存帮助类,重spring容器中获取bean
 * @author: 天问
 * @create: 2018-11-13 09:35
 **/
@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        applicationContext = ctx;
    }

    /**
     * Get application context from everywhere
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * Get bean by class
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * Get bean by class name
     *
     * @param name
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }
}

使用案例

创建一个环境变量配置文件
CrmProperties.java

package hai.guo.novel.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * <p>
 * ** 系统环境变量设置 **
 * </p>
 *
 * @author douguohai
 * @since 2019-10-16
 */
@Component
public class CrmProperties {

    /**
     * 执行环境 opencv 静态库文件地址
     */
    @Value("${libraryPath}")
    private String libraryPath;

    private CrmProperties() {
    }

    public String getLibraryPath() {
        return libraryPath;
    }
}
实际操作
/**
 * opencv的一些通用方法工具类
 */
public class GeneralUtils {

    private static final int BLACK = 0;
    private static final int WHITE = 255;

    // 设置归一化图像的固定大小
    private static final Size dsize = new Size(32, 32);

    private static String libraryPath;

    static {
        try {
            CrmProperties crmProperties=ApplicationContextHolder.getBean(CrmProperties.class);
            libraryPath=crmProperties.getLibraryPath();
            System.load(libraryPath);
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("未找到opencv库",-1);
        }
    }
}

上面的代码中,先封装一个bean来初始化相关的配置,然后利用工具类在静态代码块中获取到这个bean对象,用这个bean对象来初始化工具类中的相关属性。nb的用法

总结

spring框架非常的强大,使用方法多多,要多积累经验,根据不同的需求采用不同的手段。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值