春季:如何为静态字段注入值? -在@BeforeClass

时间:2018-09-05 17:26:13

标签: spring-boot junit4 autowired

这个问题类似于这个问题:Spring: How to inject a value to static field?

但有一点曲折。

我需要在静态方法@BeforeClass@AfterClass中使用注入的值。

我尝试创建@Component并将application.properties中的值提供给@PostConstruct上的静态字段

A ...我得到一个空指针异常。

因此,该问题可以改写为

“我如何在@AfterClass / @BeforeClass方法中使用应用程序属性中的值?”


@Component

package com.vulog.pdfgenerator.config;

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

import javax.annotation.PostConstruct;

    @Component
    public class GlobalValue {

        @Value("${spring.thymeleaf.prefix}")
        protected String prefix;

        @Value("${template.tmpfolder}")
        private String tmpfolder;
        public static String tmpFolderStatic;

        @Value("${template.classpath}")
        private String classpath;
        public static String classpathStatic;

        /**
         * Hack! we want to use the static methods BeforeClass/AfterClass
         * so the app property values should be kept static as well.
         */

        @PostConstruct
        public void init(){
            classpathStatic = classpath;
            tmpFolderStatic = tmpfolder;
        }
    }

我将其自动连接到测试类,并尝试获取GlobalValue.classpathStatic但它抛出了。

@Autowired
    GlobalValue globalValue;

0 个答案:

没有答案