方案一:使用@PostConstruct註解app
首先,聲明一個靜態變量staticTarget,靜態變量staticTarget的類型要和非靜態變量target的類型一致。 而後,在帶有@PostConstruct註解的方法中,將target的值賦給staticTarget。 最後,在靜態方法中經過調用靜態變量staticTarget來實現對非靜態變量target的調用。 說明: 1)在指定方法上加上@PostConstruct 註解來指定該方法是在bean初始化以後調用 2)在指定方法上加上@PreDestroy 註解來指定該方法是在bean銷燬以前調用
方案二:使用@PostConstruct註解ide
首先,聲明一個靜態變量factory,這個靜態變量factory的類型爲該類自身。 而後,在帶有@PostConstruct註解的方法中,將this賦給這個靜態變量factory,此時,factory指向了一個該類的實例(在容器啓動的時候建立),故factory能夠訪問到該實例中的字段。 最後,在靜態方法中,經過調用靜態變量factory來訪問該類中的非靜態變量。 例子: @Component public class FailureTool { /* // 方案一: @Autowired private MailUtil target1; @Autowired private ThreadPoolTaskExecutor target2; private static MailUtil staticTarget1; private static ThreadPoolTaskExecutor staticTarget2; @PostConstruct public void init(){ staticTarget1 = target1; staticTarget2 = target2; }*/ // 方案二: @Autowired private MailUtil mailUtil; @Autowired private ThreadPoolTaskExecutor taskExecutor; private static FailureTool factory; @PostConstruct public void init(){ factory = this; } public static void sendMail(AccountQuotaMonitor accountQuotaMonitor) { /* // 方案一 SendMailTask sendMailTask = new SendMailTask(staticTarget1, accountQuotaMonitor); FutureTask<Integer> futureTask = new FutureTask<Integer>(sendMailTask); staticTarget2.submit(futureTask); */ // 方案二 SendMailTask sendMailTask = new SendMailTask(factory.mailUtil, accountQuotaMonitor); FutureTask<Integer> futureTask = new FutureTask<Integer>(sendMailTask); factory.taskExecutor.submit(futureTask); } }
方案三:經過實現ApplicationContextAware接口來獲取到Spring的ApplicationContext,進而能夠獲取到容器中的任何對象。this
說明: 1)實現ApplicationContextAware接口的類,Spring在實例化該類時會自動調用setApplicationContext方法, 2)在setApplicationContext方法中,將類型爲ApplicationContext的入參的值賦值給該類的一個靜態變量, 3)而後就能夠經過調用靜態的getApplicationContext方法來獲取到該類的靜態變量,也即獲取到了ApplicationContext。 例子: @Component // 注:必須添加@Component註解,由於該類的實例化操做必須由Spring來完成。 public class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // TODO Auto-generated method stub ApplicationContextUtil.context = applicationContext; } public static ApplicationContext getApplicationContext() { return context; } } public class FailureTool { private static MailUtil mailUtil; private static ThreadPoolTaskExecutor taskExecutor; static { mailUtil = ApplicationContextUtil.getApplicationContext().getBean(MailUtil.class); taskExecutor = ApplicationContextUtil.getApplicationContext().getBean(ThreadPoolTaskExecutor.class); } public static void sendMail(AccountQuotaMonitor accountQuotaMonitor) { SendMailTask sendMailTask = new SendMailTask(mailUtil, accountQuotaMonitor); FutureTask<Integer> futureTask = new FutureTask<Integer>(sendMailTask); taskExecutor.submit(futureTask); } }