嗨,我尝试了一种非常简单的方法,可以澄清您的答案。
以下是我使用两个接口和两个 bean 类构建的代码。
第一个名为 Job 的接口。
public interface Job {
public void setmyJob(String myJob);
public String getmyJob();
}
和一个类来实现这个接口,名称为 MyJob
public class MyJob implements Job {
public String myJob;
public MyJob() {
System.out.println("From MyJob default Constructor and the ID= "+this);
}
public void setmyJob(String myJob) {
this.myJob=myJob;
}
public String getmyJob() {
return myJob;
}
}
在下一步中,我创建了另一个名为 Service 的接口
public interface Service {
public void setJob(Job job);
public Job getJob();
}
然后另一个类来实现这个服务接口。
public class MyService implements Service {
public Job job;
public void setJob(Job job) {
this.job=job;
System.out.println("Hello from Myservice: Job ID="+job);
}
public Job getJob() {
return job;
}
}
然后我用 main 函数在主类上创建并编写代码如下:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApplication {
public static void main(String...a) {
BeanFactory beanfactory=new ClassPathXmlApplicationContext("Beans.xml");
MyService myservice=(MyService)beanfactory.getBean("myservice");
System.out.println("Before print");
System.out.println(myservice.getJob().getmyJob());
}
}
在我的 Beans.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-3.0.xsd">
<bean id="myjob" class="MyJob">
<property name="myJob" value="My First String"/>
</bean>
<bean id="myservice" class="MyService">
<property name="job" ref="myjob"/>
</bean>
</beans>
我也参考了另一个在线教程,然后得到了这种解决方案。如果您对此代码有任何问题,请告诉我。它对我有用。