通过注释类来加载应用程序上下文

时间:2012-07-20 17:29:40

标签: java spring

我是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>

现在我想使用myString中的以下代码显示自动连接的字符串RunTestSpring.java(在TestSpring.java中声明)的值:

package mytest;

public class RunTestSpring {

    public static void main(String[] args) {
        TestSpring testInstance = new TestSpring();
        testInstance.showString();

    }

}

现在我的问题是,是否可以在加载应用程序上下文时成功运行“RunTestSpring.java”,只需注释RunTestSpring.java。如果是,使用哪个注释?

2 个答案:

答案 0 :(得分:2)

我建议编写一个JUnit类,它将使用spring注入进行环境初始化。像这样的东西 -

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="/spring/spring-wireup.xml", inheritLocations = true)
public class MyTestCase extends TestCase {
    // your test methods ...
}

答案 1 :(得分:2)

@Configurable可能就是你要找的东西,它将确保Spring没有实例化的对象可以让它们的依赖关系由Spring自动连接。然而,问题是它需要AspectJ编译时间/加载时间编织才能工作(而不是Spring AOP)。

这是一个参考: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/aop.html#aop-atconfigurable