1、创建一个Maven JAVA项目: exp6_setjection;
2、在pom.xml中配置
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
</dependencies>
3、实现Brand.java、Ford.java、Golf.java(参考示例文件)
Golf:
package org.exp6_setjection;
public class Golf implements Brand {
public String brand() {
// TODO Auto-generated method stub
return ("高尔夫");
}
}
Ford:
package org.exp6_setjection;
public class Ford implements Brand {
public String brand() {
// TODO Auto-generated method stub
return ("福特");
}
}
Brand:
package org.exp6_setjection;
public interface Brand {
public String brand();
}
4、实现Car.java;
ps:注意这里的getBrand方法里,不能直接用生成的函数代码,要用brand类调用brand()方法
package org.exp6_setjection;
import org.exp6_setjection.Brand;
public class Car {
private Brand brand;
// 代码实现:添加getBrand()方法和setBrand()方法
public String getBrand() {
return brand.brand();
}
public void setBrand(Brand brand) {
this.brand = brand;
}
}
5、实现CarApp.java
package org.exp6_setjection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class CarApp {
public static void main( String[] args )
{
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
//代码实现:添加业务逻辑代码
Car car = null;
car = (Car) ctx.getBean("carGolf");
System.out.println(car.getBrand());
car = (Car) ctx.getBean("carFord");
System.out.println(car.getBrand());
}
}
6、在src目录下配置applicationContext.xml;
这里的bean要写包的全称:
否则报错
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!--定义第一个Bean,注入Car类对象-->
<bean id="carGolf" class="org.exp6_setjection.Car">
<!--property元素用来指定需要容器注入的属性,依赖注入golf-->
<property name="brand" ref="golf"></property>
</bean>
<!--定义第2个Brand,注入Golf类对象-->
<bean id="golf" class="org.exp6_setjection.Golf"></bean>
<!--定义第一个Bean,注入Car类对象-->
<bean id="carFord" class="org.exp6_setjection.Car">
<!--property元素用来指定需要容器注入的属性,依赖注入golf-->
<property name="brand" ref="ford"></property>
</bean>
<!--定义第2个Brand,注入Golf类对象-->
<bean id="ford" class="org.exp6_setjection.Ford"></bean>
</beans>
7、运行程序CarApp。