【发布时间】:2014-08-14 11:56:05
【问题描述】:
我目前正在尝试在我的桌面应用程序中实现 Spring 依赖注入(我只是尝试注入我的服务)。
显然,尽管有所有教程(尽管其中大多数都针对 Web 应用程序),但我并不真正了解它是如何工作的。所以目前的状态是我在 pom.xml 中添加了一个依赖项来添加 spring jar,它可以正常工作。我还设法扫描了我的服务。应用上下文.xml:
<beans
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans">
<context:annotation-config />
<context:component-scan base-package="FireworksApp" />
</beans>
我很确定我必须告诉 Spring 我的 application-Context.xml 在哪里。因此我在指南中找到了一个加载器类:
public class ApplicationContextLoader {
protected ConfigurableApplicationContext applicationContext;
public ConfigurableApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* Loads application context. Override this method to change how the
* application context is loaded.
*
* @param configLocations
* configuration file locations
*/
protected void loadApplicationContext(String... configLocations) {
applicationContext = new ClassPathXmlApplicationContext(
configLocations);
applicationContext.registerShutdownHook();
}
/**
* Injects dependencies into the object. Override this method if you need
* full control over how dependencies are injected.
*
* @param main
* object to inject dependencies into
*/
protected void injectDependencies(Object main) {
getApplicationContext().getBeanFactory().autowireBeanProperties(
main, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
}
/**
* Loads application context, then injects dependencies into the object.
*
* @param main
* object to inject dependencies into
* @param configLocations
* configuration file locations
*/
public void load(Object main, String... configLocations) {
loadApplicationContext(configLocations);
injectDependencies(main);
}
}
不幸的是,这个加载器只加载给定对象的依赖项。但我不想为我拥有的每个面板手动加载依赖项。所以最后一个问题是:如何告诉 Spring 我的 applicationContext 在哪里,并自动注入所有依赖项,而不必为每个对象手动加载它?
【问题讨论】:
标签: java spring dependency-injection autowired