Spring配合接口實現解耦原理

一個簡單的接口: java

public interface ChangLetter {
	public String change();
}



兩個實現:
package com.pas.service;

import com.inter.ChangLetter;

public class LowLetter implements ChangLetter {

	private String str;

	@Override
	public String change() {
		// 大寫-》小寫
		return str.toLowerCase();
	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}
}



package com.pas.service;

import com.inter.ChangLetter;

public class UpLetter implements ChangLetter {

	private String str;

	@Override
	public String change() {

		// 小寫-》大寫
		return str.toUpperCase();
	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

}



spring配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans 'dtd'>
	<!--<bean id="changeLetter" class="com.pas.service.UpLetter">
		<property name="str" value="abcdefg" />
	</bean> -->
	 <bean id="changeLetter" class="com.pas.service.LowLetter"> <property 
		name="str" value="ABCDEFG" /> </bean>
</beans>



使用模擬view:
public class Test {
	public static void main(String[] args) {

		ApplicationContext ac= new ClassPathXmlApplicationContext("com/pas/service/beans.xml");
		ChangLetter change= (ChangLetter) ac.getBean("changeLetter");
		System.out.println(change.change());
	}
}
從新配置Spring配置文件 代碼無需更改
相關文章
相關標籤/搜索