spring笔记2_接口编程

spring控制反转接口编程:

首先编写接口interfere:ChangeLetter.java

package cn.hyl.hsp.inter;

public interface ChangeLetter {
	public String change();
}

 其次编写实现接口类:UpperLetter.java,LowwerLetter.java

package cn.hyl.hsp.inter;

public class UpperLetter implements ChangeLetter{
	private String str;
	@Override
	public String change() {
		
		return str.toLowerCase();
	}
	public String getStr() {
		return str;
	}
	public void setStr(String str) {
		this.str = str;
	}
	

}
package cn.hyl.hsp.inter;

public class LowwerLetter implements ChangeLetter{
	private String str;
	@Override
	public String change() {
		
		return str.toUpperCase();
	}
	public String getStr() {
		return str;
	}
	public void setStr(String str) {
		this.str = str;
	}
	

}

 然后在beans.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:context="http://www.springframework.org/schema/context"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	<bean id="changeLetter" class="cn.hyl.hsp.inter.UpperLetter">
		<property name="str" value="ABRTY" />
	</bean>
</beans>

 最后调用实现程序:

package cn.hyl.hsp.inter;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class App {
 
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext ac=new ClassPathXmlApplicationContext("cn/hyl/hsp/inter/beans.xml");
ChangeLetter changeLetter=(ChangeLetter) ac.getBean("changeLetter");
System.out.println(changeLetter.change());
 
}
 
}

 总结:可以减少层(web) 业务层的耦合度.

猜你喜欢

转载自hylxinlang.iteye.com/blog/1930555