静态方法中使用service

静态方法中使用Service实践
本文介绍了一种在静态方法中使用Service的设计模式,并通过具体示例解释了如何实现这一模式。文中展示了一个名为DockerUtil的类,该类通过@Autowired注解注入了EvaluationService,并在静态方法buildImages中调用了非静态成员变量dockerUtil所引用的实例的方法来使用这个Service。

静态方法中使用service

静态方法中使用service的解决办法:

public class DockerUtil {

    @Autowired
    EvaluationService evaluationService;
    
    @Autowired
    private static DockerUtil dockerUtil;

    @PostConstruct
    public void init() {
        dockerUtil = this;
    }

    //执行 docker build 命令
    public static void buildImages(String no){
        File file = new File(dockerfileDir);
        try{
            log.info("业务代码:{}",exec);
        }catch (Exception e){
            //使用evaluationService
            dockerUtil.evaluationService.modifyStatusByNo(no, EvaluationState.Error);
        }
    }

}

静态方法中调用`service`的实现方式主要有以下几种: #### 方式一:使用`@Component`和`@PostConstruct` 这种方式通过将工具类交给 Spring 管理,并在初始化时将实例赋值给静态变量,从而在静态方法中调用`service`。 ```java @Component public class ServiceUtil { @Autowired private YourService yourService; private static ServiceUtil serviceUtil; @PostConstruct public void init() { serviceUtil = this; serviceUtil.yourService = this.yourService; } public static void update(Object object) { serviceUtil.yourService.update(object); } } ``` #### 方式二:注入`ApplicationContext`并使用`getBean()`方法 在自定义工具类中注入`ApplicationContext`对象,使用`getBean()`方法获取`Service`层的`Bean`实例。 ```java public class YourCustomUtils { private ApplicationContext applicationContext; public YourCustomUtils(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public void yourMethod() { YourServiceClass yourService = applicationContext.getBean(YourServiceClass.class); // 在这里可以使用yourService调用Service层的方法 } } ``` #### 方式三:将静态属性以入参方式传入方法并注入 Spring 容器 将静态属性以入参(形参)的方式传入一个方法中,然后将此方法通过`@Autowired`注入到 Spring 容器中。 ```java public class TestStatic2 { public static CrmCustomerManageService crmCustomerManageService; } @Service public class SomeService { @Autowired public void setService(CrmCustomerManageService crmCustomerManageService) { TestStatic2.crmCustomerManageService = crmCustomerManageService; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值