Spring中提供一些Aware相关接口,像是BeanFactoryAware、 ApplicationContextAware、ResourceLoaderAware、ServletContextAware等等,实现这些 Aware接口的Bean在被初始之后,可以取得一些相对应的资源。例如实作ApplicationContextAware的Bean,在Bean被初始后,将会被注入 ApplicationContext的实例等等。 Bean取得BeanFactory、ApplicationContextAware的实例目的是什么,一般的目的就是要取得一些档案资源的存取、相 关讯息资源或是那些被注入的实例所提供的机制
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContext;
import org.springframework.beans.BeansException;
public class GlobalParamUtils implements ApplicationContextAware {
private static ApplicationContext ac;public void setApplicationContext(ApplicationContext arg0) throws BeansException {
this.ac = arg0;
}
public static String generateCodeByType(String type) {
String result = "";
if (ac.containsBean("swmsBussinessCodeManager")) {
BussinessCodeManager codeManager = (BussinessCodeManager) ac.getBean("swmsBussinessCodeManager");
try {
Method method = codeManager.getClass().getMethod(type, new Class[0]);
result = (String) method.invoke(codeManager, new Object[0]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
return result;
}
}
//swmsBussinessCodeManager在bean中的配置
<bean class="com.vtradex.swms.server.service.GlobalParamUtils"/>
<bean id="swmsBussinessCodeManager" parent="abstractTransactionProxy">
<property name="target">
<bean class="com.vtradex.swms.server.service.sequence.pojo.DefaultBussinessCodeManager" parent="baseManager">
<constructor-arg index="0">
<ref bean="sequenceGenerater"/>
</constructor-arg>
<constructor-arg index="1">
<ref bean="swmsSequenceDao"/>
</constructor-arg>
</bean>
</property>
</bean>
基本上,Spring虽然提供了这些Aware相关接口,然而Bean上若实现了这些界面,就算是与Spring发生了依赖,从另一个角度来看,虽然您可以直接在Bean上实现这些接口,但您也可以透过setter来完成依赖注入,例如:
public class GlobalParamUtils {
private static ApplicationContext ac;public void setApplicationContext(ApplicationContext arg0) throws BeansException {
this.ac = arg0;
}
public static String generateCodeByType(String type) {
String result = "";
if (ac.containsBean("swmsBussinessCodeManager")) {
BussinessCodeManager codeManager = (BussinessCodeManager)ac.getBean("swmsBussinessCodeManager");
try {
Method method = codeManager.getClass().getMethod(type, new Class[0]);
result = (String) method.invoke(codeManager, new Object[0]);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
return result;
}
}
注意这次我们并没有实作ApplicationContextAware,我们在程序中可以自行注入ApplicationContext实例:
ApplicationContext context = new ClassPathXmlApplicationContext("service.xml");
就Bean而言,降低了对Spring的依赖,可以比较容易从现有的框架中脱离