1. 程式人生 > >直接new 物件 Spring 不會注入的解決方法

直接new 物件 Spring 不會注入的解決方法

1.建一個類實現ApplicationContextAware介面,有一個引用ApplicationContext的靜態成員,然後,遺留系統需要引用spring管理的bean的地方,使用這個類。

package com.eliteams.quick4j.web.utils;

import com.eliteams.quick4j.web.listenner.ListennerTask;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import
org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Service; /** * Created by 18358 on 2016/11/25. */ public class SpringContext implements ApplicationContextAware { protected static ApplicationContext context; @Override public void setApplicationContext
(ApplicationContext applicationContext) throws BeansException { context = applicationContext; } public static ApplicationContext getContext() { return context; } }

2.然後在spring配置檔案里加

<bean id="springContext" class="com.eliteams.quick4j.web.utils.SpringContext"></bean
>

3.其它類中涉及到引用時 採用下面的方法即可解決,當然自己也可以寫個通用的工廠類方法

 MyBean myBean = (MyBean) SpringContext.getContext().getBean("myBean");