[英]Loading an application context by annotating a class
我是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>
現在我想使用RunTestSpring.java中的以下代碼顯示自動連接的字符串myString
(在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”。 如果是,使用哪個注釋?
我建議編寫一個JUnit類,它將使用spring注入進行環境初始化。 像這樣的東西 -
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="/spring/spring-wireup.xml", inheritLocations = true)
public class MyTestCase extends TestCase {
// your test methods ...
}
@Configurable
可能就是您正在尋找的,它將確保Spring未實例化的對象可以通過Spring自動連接它們的依賴項。 然而,問題是它需要AspectJ編譯時間/加載時間編織才能工作(而不是Spring AOP)。
以下是一個參考: http : //static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/aop.html#aop-atconfigurable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.