I have a MainClass which have 2 variables. I would like to pass those 2 values to a springframework bean class "Test". how do I define that in applicationContext.xml and also how do I pass those 2 variable values to the bean "Test".
Ex:
class MainClass {
public int var1;
public int var2;
public Test test;
public void setVar1(int var11) {
var1 = var11;
}
public void setVar2(int var22) {
var2 = var22;
}
public static void main(String args[]) {
ApplicationContext context =
new FileSystemXmlApplicationContext("applicationContext.xml");
Test = context.getBean("test");
}
}
------------ TEST class ------------
public class Test {
public Test (int var1, int var2) {}
}
------------- applicationContext.xml -------------
<bean id="test" class="com.path.test">
<constructor-arg index="0" type="int" value="????"/>
<constructor-arg index="1" type="int" value="????"/>
</bean>
You can pass values in like this:
<bean id="test" class="com.path.test.Test">
<constructor-arg index="0" type="int" value="123"/>
<constructor-arg index="1" type="int" value="456"/>
</bean>
You should remember to put your fully-qualified class name as the value of the class
attribute.
That said, your Test
class is not holding onto its state. If you want to get a hold of the values you specified in your applicationContext.xml
, you should create some members of Test
:
public class Test {
private int v1;
private int v2;
public Test (int var1, int var2) {v1 = var1; v2 = var2;}
public int getVOne() {
return v1;
}
public int getVTwo() {
return v2;
}
}
You should then be able to access these in your main
method like this:
public static void main(String args[]) {
ApplicationContext context =
new FileSystemXmlApplicationContext("applicationContext.xml");
Test test = context.getBean("test");
int v1 = test.getVOne();
int v2 = test.getVTwo();
System.out.println("V1: " + v1 + " V2: " + v2); //output: V1: 123 V2: 456
}