简介

说明

本文用示例介绍Spring如何将组件注入到静态工具类。

需求

在Controller层想使用一个静态工具,这个静态工具要使用其他组件。

错误方法:在静态字段上注入

Controller

package com.example.controller;

import com.example.component.WelcomeUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
@GetMapping("/test")
public String test() {
WelcomeUtil.welcome();
return "test success";
}
}

工具类

package com.example.component;

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

@Component
public class WelcomeUtil {
@Autowired
private static Hello hello;

public static void welcome() {
hello.sayHello();
}
}

引入的组件

package com.example.component;

import org.springframework.stereotype.Component;

@Component
public class Hello {
public void sayHello() {
System.out.println("Hello");
}
}

测试

访问:​​http://localhost:8080/test​

SpringBoot--将组件注入到静态工具类--方法/实例_工具类

后端结果

SpringBoot--将组件注入到静态工具类--方法/实例_ide_02

方案1:构造器注入

其余代码与上边相同

工具类

package com.example.component;

import org.springframework.stereotype.Component;

@Component
public class WelcomeUtil {
private static Hello hello;

public WelcomeUtil(Hello hello) {
WelcomeUtil.hello = hello;
}

public static void welcome() {
hello.sayHello();
}
}

测试

访问:​​http://localhost:8080/test​

SpringBoot--将组件注入到静态工具类--方法/实例_ide_03

后端结果

SpringBoot--将组件注入到静态工具类--方法/实例_Spring_04

方案2:setter注入

其余代码与上边相同

工具类

package com.example.component;

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

@Component
public class WelcomeUtil {
private static Hello hello;

public static void welcome() {
hello.sayHello();
}

@Autowired
public void setHello(Hello hello) {
WelcomeUtil.hello = hello;
}
}

测试

访问:​​http://localhost:8080/test​

结果

SpringBoot--将组件注入到静态工具类--方法/实例_Spring_05

后端结果

SpringBoot--将组件注入到静态工具类--方法/实例_ide_06

方案3:ApplicationContext工具类

ApplicationContext工具类

package com.example.util;

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

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
private static ApplicationContext context;

@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
ApplicationContextHolder.context = context;
}

public static ApplicationContext getContext() {
return context;
}
}

工具类

package com.example.component;

import com.example.util.ApplicationContextHolder;
import org.springframework.stereotype.Component;

@Component
public class WelcomeUtil {
public static void welcome() {
ApplicationContextHolder.getContext()
.getBean(Hello.class).sayHello();

}
}

测试

访问:​​http://localhost:8080/test​

结果

SpringBoot--将组件注入到静态工具类--方法/实例_工具类_07

后端结果

SpringBoot--将组件注入到静态工具类--方法/实例_Spring_08