Spring 静态注入

[toc]

Spring 静态注入

一、 @Value静态注入方式

@Slf4j
@Component
public class ReplaceUtil {


    public static String env;

    @Value("${movie.env}")
    public void setEnv(String env) {
        this.env = env;
    }
    /**
     * @Author shadow
     * @param targetUrl
     */
    public static String appendHead(String targetUrl) {
        if (StringUtils.isEmpty(targetUrl)) {
            return null;
        }
        StringBuilder head = new StringBuilder();
        head.append("dev".equals(env) ? "http:" : "https:").append(targetUrl);
        return head.toString();
    }
}

二、注解@PostConstruct方式

@Component
public class SecurityLogic {

    @Autowired
    private PropertyConfigurer propertyConfigurerTmp;
    
    private static PropertyConfigurer propertyConfigurer;

    @PostConstruct
    public void init() {
        SecurityLogic.propertyConfigurer = propertyConfigurerTmp;
    }

    public static void encrypt(String param) throws Exception {
        String encryptType=propertyConfigurer.getProperty("encryptType");
        //todo
    }
}

三、set方法上面添加注解方式

@Component
public class SecurityLogic {

    private static PropertyConfigurer propertyConfigurer;

    @Autowired
    public void setPropertyConfigurer(PropertyConfigurer propertyConfigurer) {
        SecurityLogic.propertyConfigurer = propertyConfigurer;
    }

    public static void encrypt(String param) throws Exception {
        String encryptType=propertyConfigurer.getProperty("encryptType");
        //todo
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容