Person接口:
public interface Person {
// 定义使用斧子的方法
public void useAxe();
}
Spring推荐面向接口编程,这样可更好地让规范和实现分离,从而提供更好的解耦;对于一个Java EE应用,不管是DAO组件还是业务逻辑组件,都应该先定义一个接口,该接口定义了该组件应实现的功能,但功能的实现则由其实现类提供
Axe接口:
public interface Axe {
// Axe接口里有个砍的方法
public String chop();
}
实现Axe:
public class StoneAxe implements Axe {
public String chop() {
return "石斧砍柴好慢S";
}
}
<?xml version="1.0" encoding="UTF-8"?> <!-- Spring配置文件的根元素,使用spring-beans-3.0.xsd语义约束 --> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 配置chinese实例 --> <bean id="chinese" class="com.Chinese"> <!-- 将stoneAxe注入给axe属性 --> <property name="axe" ref="stoneAxe" /> </bean> <!-- 配置stoneAxe实例 --> <bean id="stoneAxe" class="com.StoneAxe" /> </beans>
public class BeanTest {
public static void main(String[] args) {
// 创建Spring容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
// 获取chinese实例
Person p = ctx.getBean("chinese", Person.class);
// 调用useAxe()方法
p.useAxe();
}
}
public class Chinese implements Person {
private Axe axe;
// 默认的构造器
public Chinese() {
}
// 构造注入所需的带参数的构造器
public Chinese(Axe axe) {
this.axe = axe;
}
// 实现Person接口的useAxe方法
@Override
public void useAxe() {
// 调用axe的chop()方法
// 表明Person对象依赖于axe对象
System.out.println(axe.chop());
}
}
<?xml version="1.0" encoding="UTF-8"?> <!-- Spring配置文件的根元素,使用spring-beans-3.0.xsd语义约束 --> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 配置chinese实例 --> <bean id="chinese" class="com.Chinese"> <!-- 使用构造注入,为chinese实例注入stoneAxe实例 --> <constructor-arg ref="stoneAxe" /> </bean> <!-- 配置stoneAxe实例 --> <bean id="stoneAxe" class="com.StoneAxe" /> </beans>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有