下面的朋友是我的代码,我正在尝试使用 Spring 运行依赖注入
我有一个接口,该接口的两个类实现。
一个 bean.xml 和一个主要方法类。
接口 IWriter.java
package DI;
public interface IWriter {
public void writer(String s);
}
类 Writer.java
package DI;
import org.springframework.stereotype.Service;
@Service
public class Writer implements IWriter {
public void writer (String s){
System.out.println(s);
}
}
类 NiceWriter.java
package DI;
import org.springframework.stereotype.Service;
@Service
public class NiceWriter implements IWriter {
public void writer (String s){
System.out.println("The string is " + s);
}
}
另一个班级
package DI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
@Service
public class MySpringBeanWithDependency {
@Autowired
private IWriter writer;
public void run() {
String s = "This is my test";
writer.writer(s);
}
}
主.java
package DI;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import DI.MySpringBeanWithDependency;
public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
BeanFactory factory = context;
MySpringBeanWithDependency test = (MySpringBeanWithDependency) factory.getBean("mySpringBeanWithDependency");
test.run();
}
}
bean.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="DI" />
</beans>
当我运行代码时,Spring 容器给出了 Writer.java 类的方法的输出。我还没有指定选择哪个实现。Spring 是如何实现 Writer.java 的?