<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>st.com</groupId> <artifactId>springdemo</artifactId> <version>1.0-SNAPSHOT</version> <properties> <!-- Generic properties --> <java.version>1.8</java.version> <!-- Spring --> <spring-framework.version>4.3.3.RELEASE</spring-framework.version> </properties> <dependencies> <!-- Spring and Transactions --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-framework.version}</version> </dependency> </dependencies> <build> <finalName>springdemo</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>
import java.util.List; public interface Books { List<String> getBooks(); }
import java.util.ArrayList; import java.util.List; public class JavaBooks implements Books { @Override public List<String> getBooks() { ArrayList<String> books = new ArrayList<String>(); books.add("Java Complete Reference"); books.add("Spring in Action"); return books; } }
public class Catalog { private Books books; public void setBooks(Books books) { this.books = books; } public void print() { for (String book : books.getBooks()) { System.out.println(book); } } }
<?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="javabooks" class="JavaBooks" /> <bean id="catalog" class="Catalog"> <property name="books" ref="javabooks"></property> </bean> </beans>
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml"); Catalog cat = context.getBean("catalog", Catalog.class); cat.print(); } }