i am new with the Spring Framework and I tried the following example:
First I created two very simple classes
public class ObjectA {
@Override
public String toString() {
return "I am ObjectA";
}
}
public class ObjectB {
@Override
public String toString() {
return "I am ObjectB";
}
}
No I want to use this Classes managed by Spring. So I made another Class which uses the @Resource (javax.annotation.Resource) Annotiation for wiring the two Objects.
public class MyApp {
@Resource
public ObjectA oa;
@Resource
public ObjectB ob;
public void info() {
System.out.println("--------------");
System.out.println(oa);
System.out.println("--------------");
System.out.println(ob);
System.out.println("--------------");
}
public static void main( String[] args ) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("mySpringConfig.xml");
System.out.println(applicationContext.getBean( ObjectA.class ));
System.out.println(applicationContext.getBean( ObjectB.class ));
MyApp myApp = applicationContext.getBean( MyApp.class );
myApp.info();
}
}
The mySpringConfig.xml contains this:
[..]
<bean id="objectA" class="com.mySpringCompany.ObjectA" />
<bean id="objectb" class="com.mySpringCompany.ObjectB" />
<bean id="myApp" class="com.mySpringCompany.MyApp" />
[..]
Now when I run the Main-Method of MyApp I get the following:
I am ObjectA
I am ObjectB
--------------
null
--------------
null
--------------
So when I directly use applicationContext.getBean( ObjectA.class ) in the main-method I get an instance of ObjectA. When I want to get within the MyApp Object it doesn't work. But I think Spring should have injected the two Objects in the MyApp class. What does i made wrong? Thanks in advance for every help.
Aucun commentaire:
Enregistrer un commentaire