Bud*_*dhi 8 java spring dependency-injection inversion-of-control
我想用IOC编写一个独立的应用程序,如何在那里使用spring依赖注入?我正在使用JIdea.有弹簧2.5支持,但我想使用弹簧3.0这里是我尝试的方式!
我有使用Spring MVC的经验,我们可以在WebApplicationContext中注入依赖项,但是如何在独立的应用程序中注入依赖项
我试过这个
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"com\\ttg\\xmlfile.xml"});
但是我看不到依赖项是由那里定义的bean注入的(在XML文件中)我把上面的代码放在main方法中,两个bean的两个bean定义,在一个Java类的构造函数中我使用了另一个类的对象 - 注入到这个对象 - 并调用一个方法,它将打印一些东西,但它没有工作我认为上面的代码创建所有依赖项并注入它们但它似乎不是那样的
如何在不包含WebApplicationContext的独立应用程序中正确使用Springs IOC,依赖注入?
请提一下步骤.
Mih*_*der 18
假设你有:
class Bean1 {
Bean2 bean2;
}
class Bean2 {
String data;
}
Run Code Online (Sandbox Code Playgroud)
context.xml文件
<bean id="bean1" class="Bean1">
<property name="bean2" ref="bean2" />
</bean>
<bean id="bean2" class="Bean2" />
Run Code Online (Sandbox Code Playgroud)
那应该是真的
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"context.xml"});
Bean1 bean1 = (Bean1) context.getBean("bean1");
// bean1.bean2 should not be null here.
Run Code Online (Sandbox Code Playgroud)
您可以使用spring提供的自动装配支持,以便将依赖关系(并可能应用后处理器)注入不属于应用程序上下文的对象.
在您的情况下,此对象是您的独立应用程序.
这是实现这一目标的方法.在这个例子中,我使用@Autowired(对于b1),传统的DI(对于b2)和b3的初始化钩子.带注释的自动装配支持假定您已在应用程序上下文中定义了适当的弹簧后处理器(例如,通过声明<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
}
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,所有b1,b2和b3都应为非null(假设应用程序上下文中存在b1和b2 bean).
我没有测试过它(可能因为一些错字而无法编译),但这个想法是在最后3行.请参阅javadocs AutowireCapableBeanFactory并提及方法以确切了解发生的情况.
| 归档时间: |
|
| 查看次数: |
14370 次 |
| 最近记录: |