Spring - 如何使用 Spring 依赖注入编写独立的 Java 应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/865149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring- How to use Spring Dependency Injection to write a Standalone Java Application
提问by Buddhi
I want to write a standalone application with IOC, how do I use springs dependency injection in there? I'm using JIdea. There is spring 2.5 support but I want to use spring 3.0 here is the way I tried!
我想用 IOC 编写一个独立的应用程序,如何在其中使用 springs 依赖注入?我正在使用 JIdea。有 spring 2.5 支持,但我想使用 spring 3.0,这是我尝试过的方式!
I experience in using Spring MVC we can inject dependencies there in a WebApplicationContext but how do I inject dependencies in a standalone application
我有使用 Spring MVC 的经验,我们可以在 WebApplicationContext 中注入依赖项,但是如何在独立应用程序中注入依赖项
I tried this
我试过这个
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"com\\ttg\\xmlfile.xml"});
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"com\\ttg\\xmlfile.xml"});
but I cannot see that the dependencies are injected by the beans defined there (in the XML file) I put the above code in the main method and two bean definitions for two Objects,in one Java class's constructor I used the other class's object - which was injected to this object - and called a method on that which will print some thing but it didn't worked I thought that the above code creates all the dependencies and injects them but it doesn't seem like that
但我看不到依赖项是由那里定义的 bean 注入的(在 XML 文件中)我将上面的代码放在 main 方法和两个对象的两个 bean 定义中,在一个 Java 类的构造函数中我使用了另一个类的对象 - 其中被注入到这个对象 - 并调用了一个方法来打印一些东西但它没有工作我认为上面的代码创建了所有依赖项并注入它们但它似乎不是那样
How do I properly use Springs IOC, dependency injection in my stand alone app which does not contain a WebApplicationContext?
如何在不包含 WebApplicationContext 的独立应用程序中正确使用 Springs IOC、依赖项注入?
Please mention steps.
请提步骤。
回答by Mihai Toader
suppose you have:
假设你有:
class Bean1 {
Bean2 bean2;
}
class Bean2 {
String data;
}
the context.xml file
context.xml 文件
<bean id="bean1" class="Bean1">
<property name="bean2" ref="bean2" />
</bean>
<bean id="bean2" class="Bean2" />
then this should be true
那么这应该是真的
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"context.xml"});
Bean1 bean1 = (Bean1) context.getBean("bean1");
// bean1.bean2 should not be null here.
回答by Gaetan
you can use autowiring support provided by spring, in order to inject dependencies (and possibly apply post processors) to an object that is not part of the application context.
您可以使用 spring 提供的自动装配支持,以便将依赖项(并可能应用后处理器)注入不属于应用程序上下文的对象。
In your case, this object is your standalone application.
在您的情况下,此对象是您的独立应用程序。
Here is the way to achieve this. In this example, I use @Autowired (for b1), traditional DI (for b2) and initialization hook for b3. The autowiring support with annotations assumes you have defined the appropriate spring post-processor in your application context (e.g. by declaring <context:annotation-config/>).
这是实现这一目标的方法。在这个例子中,我使用@Autowired(用于 b1)、传统 DI(用于 b2)和用于 b3 的初始化钩子。带有注释的自动装配支持假设您已经在应用程序上下文中定义了适当的 spring 后处理器(例如通过声明<context:annotation-config/>)。
public class StandaloneApp implements InitializingBean {
@Autowired private Bean1 b1;
private Bean2 b2;
private Bean3 b3;
public void afterPropertiesSet() throws Exception {
this.b3 = new Bean3(b1, b2);
}
public void setB2(Bean2 b2) {
this.b2 = b2;
}
public static void main(String... args) {
String[] locations = // your files relative to the classpath
ApplicationContext ac = new ClasspathXmlApplicationContext(locations);
// or use FileSystemXmlApplicationContext if the files are not in the classpath
StandaloneApp app = new StandaloneApp();
AutowireCapableBeanFactory acbf = ac.getAutowireCapableBeanFactory();
acbf.autowireBeanProperties(app, AUTOWIRE_BY_NAME, false);
acbf.initializeBean(app, "standaloneApp"); // any name will work
}
}
In this example, all b1, b2 and b3 should be non-null (assuming b1 and b2 beans exist in your application context).
在此示例中,所有 b1、b2 和 b3 都应为非空(假设应用程序上下文中存在 b1 和 b2 bean)。
I haven't tested it (might not even compile due to some typo), but the idea is in the last 3 lines. See the javadocs for AutowireCapableBeanFactoryand mentionned methods to see exactly what happens.
我还没有测试过(由于一些错字,甚至可能无法编译),但这个想法在最后 3 行中。请参阅 javadocs forAutowireCapableBeanFactory和提到的方法以确切了解发生了什么。
回答by Matt
If you prefer (mostly) pure java, you can use java config:
如果您更喜欢(主要是)纯 java,则可以使用 java 配置:
@Configuration
pubic class MyConfig {
@Bean
public Bean1 bean1() { return new Bean1(); }
@Bean
public Bean2 bean2() { return new Bean2(bean1()); }
}
And then to instantiate:
然后实例化:
ApplicationContext ctx =
new AnnotationConfigApplicationContext(MyConfig.class);
Keep in mind there's some things that pure annotation driven configuration doesn't yet support (such as things like tx:annotation-driven), which you might need some xml glue code for.
请记住,纯注释驱动配置尚不支持某些内容(例如 tx:annotation-driven 之类的内容),您可能需要一些 xml 粘合代码。
<beans>
<tx:annotation-driven />
<context:annotation-config/>
<bean class="MyConfig"/>
</beans>
And then use a standard xml based way of creating the ApplicationContext (like ClasspathXmlApplicationContext, or the spring web context loader, etc...).
然后使用基于标准 xml 的方式创建 ApplicationContext(如 ClasspathXmlApplicationContext,或 spring web 上下文加载器等...)。
回答by jpganz18
you can use the command @Autowired
您可以使用命令@Autowired
回答by Taylor Leese
Are you calling context.getBean("beanName")to get a reference to the bean or are you doing a new SomeClass()? If you do it through getBean()then the injected properties should be set.
你是打电话context.getBean("beanName")来获取对 bean 的引用还是你在做new SomeClass()? 如果你做到了,getBean()那么注入的属性应该被设置。
Also, be sure to use the same bean factory (ClassPathXmlApplicationContext instance) for retrieving all your beans. This should most likely be static final and used by the entire application.
此外,请确保使用相同的 bean 工厂(ClassPathXmlApplicationContext 实例)来检索所有 bean。这很可能是静态 final 并被整个应用程序使用。
回答by neesh
How did you confirm that your beans aren't being wired correctly? One common issue is the xml config file not being in the right place. Can you give us some more information like your project layout and the code you use to obtain the beans from the container?
你是如何确认你的 bean 没有正确连接的?一个常见问题是 xml 配置文件不在正确的位置。你能给我们一些更多的信息,比如你的项目布局和你用来从容器中获取 bean 的代码吗?
回答by duffymo
If you add log4j logging to your app, you should see a cascade of messages coming out that will tell you a lot about what Spring is and is not doing. If you don't have that feedback, you're in the dark. You might be able to ferret out the answer just by getting more information out of Spring from log4j.
如果您将 log4j 日志记录添加到您的应用程序,您应该会看到一连串的消息,这些消息会告诉您很多关于 Spring 正在做什么和不做什么的信息。如果你没有这些反馈,你就一无所知。您也许可以通过从 log4j 中获取更多来自 Spring 的信息来找出答案。

