我刚刚开始学习Spring,它很容易就能生成几个类,并通过construtor arg或setter传递Spring配置文件中的值。
如果我将一个属性引用给另一个配置文件怎么办,考虑我的两个类User和Vehical的简单程序和两个Spring COnfiguration文件FirstBean.xml和SecondBean.xml以及一个带有main方法的App类,如下所示 - < / p>
目录结构 -
User.java -
package com.common;
public class User {
public String username;
public Vehical vehical;
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Vehical getVehical() {
return vehical;
}
public void setVehical(Vehical vehical) {
this.vehical = vehical;
}
}
Vehical.java -
package com.common;
public class Vehical {
public String vehicalname;
public Vehical() {
}
public Vehical(String vehicalname) {
super();
this.vehicalname = vehicalname;
}
}
App.java -
package com.main;
import com.common.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) throws InterruptedException{
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("com/bean/FirstBean.xml");
User user =(User) context.getBean("userClass");
String s= user.toString();
System.out.println(s);
}
}
FirstBean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="com/bean/SecondBean.xml"/>
<bean id="userClass" name="User" class="com.common.User">
<property name="username" value="Sushant"></property>
<property name="vehical" ref="vehicalClass"></property>
</bean>
</beans>
SecondBean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="vehicalClass" name="Vehical" class="com.common.Vehical">
<constructor-arg value="pulser"></constructor-arg>
</bean>
</beans>
在FirstBean.xml中,我导入了SecondBean.xml资源,并使用ref引用了它,但它没有得到它。我怎么解决这个问题?我不确定我想做的事情是否可能。
答案 0 :(得分:0)
替换<import resource="com/bean/SecondBean.xml"/>
<import resource="SecondBean.xml"/>