我是新来的Spring,我想知道是否可以通过注释其变量必须注入的类来加载应用程序(而不是使用ApplicationContext ctx = new ApplicationContext(“myAppContext”)) 。通过注解类加载应用程序上下文
让我给下面的例子:
我有这个类TestSpring.java
将字符串应该被装配
package mytest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
//Is it possible to put an annotation here that loads the application context "TestSpringContext.xm"??
public class TestSpring {
@Autowired
@Qualifier("myStringBean")
private String myString;
/**
* Should show the value of the injected string
*/
public void showString() {
System.out.println(myString);
}
}
Spring bean配置文件(TestSpringContext.xml)看起来像这样
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
>
<context:annotation-config />
<bean id="myStringBean" class="java.lang.String">
<constructor-arg value="I am an injected String."/>
</bean>
</beans>
现在我想显示自动布线字符串的值使用下面的代码(在TestSpring.java声明)在RunTestSpring.java
:
package mytest;
public class RunTestSpring {
public static void main(String[] args) {
TestSpring testInstance = new TestSpring();
testInstance.showString();
}
}
现在我的问题,是有可能同时通过只标注RunTestSpring.java
加载应用程序上下文中运行“RunTestSpring.java”成功。如果是,用哪个注释?
Thx的答案,但我已经知道如何做一个JUnit测试。我想在Util类中使用TestSpring.java类(它超出了Test范围),这就是为什么注解@RunWith(SpringJUnit4ClassRunner.class)不适合这种情况。但是 – Horace 2012-07-20 18:03:29
不确定@ImportResource是否是您需要的注释。我没有尝试过。请参阅此处的文档[http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/context/annotation/Configuration.html]和一个示例[http:// www。 theserverside.com/tip/Combining-Annotation-and-XML-Configurations-in-your-Spring-3-Applications] – devang 2012-07-20 18:13:07