Bạn bè bên dưới là mã của tôi, tôi đang cố gắng chạy sự phụ thuộc Tiêm với SpringMùa xuân là chọn một giao diện thực hiện nhiều, một mình?
Tôi có một giao diện, hai triển khai lớp của giao diện đó.
One bean.xml và một lớp phương thức chính.
Interface IWriter.java
package DI;
public interface IWriter {
public void writer(String s);
}
Lớp Writer.java
package DI;
import org.springframework.stereotype.Service;
@Service
public class Writer implements IWriter {
public void writer (String s){
System.out.println(s);
}
}
Lớp 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);
}
}
lớp Một
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);
}
}
Main.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>
Khi tôi chạy container đang mùa xuân mang đến cho đầu ra của phương pháp của lớp Writer.java. Tôi không có bất kỳ nơi nào được chỉ định thực hiện để chọn. Spring sẽ chọn cách thực hiện Writer.java như thế nào?
Trước khi đăng câu hỏi, mã shuld được định dạng tốt –