spring启动的时候,在进行元数据管理的时候,会自动忽略掉static成员,包括其中的属性和方法。如果我们在static中需要调用spring管理的对象,此时可以使用以下三种方式进行注入。
比如有个TestService:
@Service
public class TestService{
public String test(){
return "test";
}
}
一、使用@PostConstruct注解
@Component
public class TestStatic{
@Autowired
private TestService testService;
private static TestStatic testStatic;
/**
* @PostConstruct该注解被用来修饰一个非静态的void()方法
*被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行
*方法执行先后顺序为: Constructor > @Autowired > @PostConstruct
*/
@PostConstruct
public void init() {
testStatic = this;
testStatic.testService= this.testService;
}
}
二、手动管理注入
public class TestStatic{
static TestStatic testStatic;
// 将静态属性以入参的方式传入,然后通过@Autowired注入到spring容器中
@Autowired
public void setTestStatic(TestStatic testStatic) {
TestStatic.testStatic = testStatic;
}
}
三、实现SmartInitializingSingleton
@Component
public class TestStatic implements SmartInitializingSingleton {
@Autowired
private AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor;
@Override
public void afterSingletonsInstantiated() {
autowiredAnnotationBeanPostProcessor.processInjection(new TestService());
}
}