1.说明

@value或者@Autowired不能直接注入值给静态属性,spring 不允许/不支持把值注入到静态变量中;spring支持set方法注入,我们可以利用非静态setter 方法注入静态变量。spring 依赖注入是依赖 set方法,set方法是普通的对象方法,static变量是类的属性。

方式1:利用set方法注入

在set方法上增加@value或者@Autowired就可以了

@Component
public class MyServiceComponet {


    private static MyService myService;

    private static String accessKeyId;

    @Autowired
    public void setMyService(MyService myServiceArg) {
        myService = myServiceArg;
    }

    @Value("accessKeyId")
    public void setAccessKeyId(String accessKeyIdArgs) {
        accessKeyId = accessKeyIdArgs;
    }

    public static MyService getMyService() {
        return myService;
    }

    public static String getAccessKeyId() {
        return accessKeyId;
    }
}

方式2:利用@PostConstruct注解

@Component
public class MyServiceComponet {


    private static MyService myService;

    private static String accessKeyId;

    @Autowired
    private MyService myServiceArg;

    @Value("accessKeyId")
    private String accessKeyIdArg;

    @PostConstruct
    public void init() {
        myService = this.myServiceArg;
        accessKeyId = this.accessKeyIdArg;
    }


    public static MyService getMyService() {
        return myService;
    }

    public static String getAccessKeyId() {
        return accessKeyId;
    }
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐