普通静态类方法获取Spring注入的Bean实体

<转载>
原本想要在静态方法中获取Spring注解后的Bean,发现给Bean字段添加static关键字后,启动tomcat报错-------错误大意是说静态字段不能注解。

packagecom.sondon.dev_info.controller;

importjavax.annotation.PostConstruct;
importjavax.annotation.PreDestroy;
importjavax.annotation.Resource;

importorg.springframework.stereotype.Controller;

importcom.sondon.dev_info.entity.DevInfo;
importcom.sondon.dev_info.service.TemplateManager;

/**
*@Project:Dev_Info_Web
*@Package:com.sondon.dev_info.controller
*@Class:Dev_Info.java
*@Company广州讯动网络科技有限公司
*@Author:蔡文锋
*@DateTime:2015年4月24日下午1:39:58
*@Blog:http://blog.csdn.net/caiwenfeng_for_23
*@Description:{}
*/

@Controller
publicclassDev_InfoController{
@Resource
publicTemplateManagertemplateManager;
privatestaticDev_InfoControllerdev_infoController;

/**
*构造方法执行后调用init()
*/
@PostConstruct
publicvoidinit(){
System.out.println("I'minitmethodusing@PostConstrut....");
dev_infoController=this;
dev_infoController.templateManager=this.templateManager;
}
/**
*servlet销毁前调用dostory()
*/
@PreDestroy
publicvoiddostory(){
System.out.println("I'mdestorymethodusing@PreDestroy.....");
}

publicstaticvoidAdd_DevInfo(DevInfodevinfo){

//booleanresult=false;
dev_infoController.templateManager.add(devinfo);
//returnresult;
}

/**
*@paramtemplateManager
*thetemplateManagertoset
*/
publicvoidsetTemplateManager(TemplateManagertemplateManager){
this.templateManager=templateManager;
}
}

从上面可以看到使用了@PostConstruct , 然后在静态方法Add_DevInfo(DevInfo devinfo)调用了 templateManager.
不了解@PostConstruct @PreDestroy的同学,可以看下面一篇文章:
http://blog.csdn.net/caiwenfeng_for_23/article/details/45249397

你可能感兴趣的:(普通静态类方法获取Spring注入的Bean实体)