我想测试一下Spring注解,看看他们如何与来自Spring 3.0 Source得出一些简单的例子(特别是在这种情况下,“@required”注释)工作。春天@Required注解工作不正常
首先,我想出了一个不使用任何注释的基本的“Hello World”式的例子。这按预期工作(即打印“Hello Spring 3.0〜!”)。
我然后加入一个DAO
物场到Spring3HelloWorld
类。我的目的是故意造成被标注为DAO
与@Required
的二传手,但随后没有将其设定为发生异常。但是,当我期待基于不遵循注解“规则/要求”的异常时,我得到空指针异常(因为this.dao
为空)。
我以为我需要设置DAO
对象之前调用Spring3HelloWorld
任何方法,但显然情况并非如此。我假设我误解了@Required
的工作原理。
所以基本上我将如何得到下面给我一个错误线沿线的“嘿,你不能这样做,你忘了设置DAO等等等等等等”。
Spring3HelloWorldTest.java:
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Spring3HelloWorldTest {
public static void main(String[] args) {
XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource ("SpringHelloWorld.xml"));
Spring3HelloWorld myBean = (Spring3HelloWorld) beanFactory.getBean("spring3HelloWorldBean");
myBean.sayHello();
}
}
Spring3HelloWorld.java:
import org.springframework.beans.factory.annotation.Required;
public class Spring3HelloWorld {
private DAO dao;
@Required
public void setDAO(DAO dao){
this.dao = dao;
}
public void sayHello(){
System.out.println("Hello Spring 3.0~!");
//public field just for testing
this.dao.word = "BANANA!!!";
}
}
SpringHelloWorld.xml:
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<bean id="dao" class="src.DAO" ></bean>
<bean id="spring3HelloWorldBean" class="src.Spring3HelloWorld" ></bean>
</beans>
啊我不知道这一点。谢谢,我一定会尝试使用ApplicationContext。 – FromCanada 2010-07-19 20:53:27
再次感谢。我测试了这两种方法,他们都工作。 – FromCanada 2010-07-19 21:13:19
+1好点... – skaffman 2010-07-20 07:28:18