static方法中注入springBean对象
spring启动的时候,在进行元数据管理的时候,会自动忽略掉static成员,包括其中的属性和方法。如果我们在static中需要调用spring管理的对象,此时可以使用以下三种方式进行注入。三、实现SmartInitializingSingleton。一、使用@PostConstruct注解。
·
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());
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)