大半天都在看spring,以前总是看不下去,这次慢慢来,慢慢看。
看那些基础的,倒是还不错。好多都是关于helloworld的,写完helloworld,觉得不怎么形象。于是写了动物,作为接口。
(1)动物接口方法:move(),say()。
(2)cat和dog ,实现接口。
package Animal; /** * Created with IntelliJ IDEA. * User: wang * Date: 13-10-22 * Time: 下午5:12 * To change this template use File | Settings | File Templates. */ public class Cat implements Animal { @Override public void move() { //To change body of implemented methods use File | Settings | File Templates. System.out.println("4 legs"); } @Override public void say() { //To change body of implemented methods use File | Settings | File Templates. System.out.println("miao miao"); } }
(3)xml文件:
<?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="cat" class="Animal.Cat" ></bean> <bean id="dog" class="Animal.Dog"></bean> <bean id="bird" class="Animal.Bird"> <constructor-arg index="0" value="gegegege"></constructor-arg> <constructor-arg index="1" value="gogogo"></constructor-arg> </bean> </beans>
xml里面,有个constructor-arg ,这个是bird里面,构造方法参数。
(4) Bird.java
package Animal; /** * 带有参数的spring bean * Created with IntelliJ IDEA. * User: wang * Date: 13-10-22 * Time: 下午6:09 * To change this template use File | Settings | File Templates. */ public class Bird implements Animal { private String message; private String movess; public Bird(String message,String movess){ this.message=message; this.movess=movess; } @Override public void say() { //To change body of implemented methods use File | Settings | File Templates. System.out.println(message); } @Override public void move() { //To change body of implemented methods use File | Settings | File Templates. System.out.println(movess); } }
构造方法里面,有两个参数,xml对应的有设置。
(5) 然后测试一下,ATest.java
package Animal; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created with IntelliJ IDEA. * User: wang * Date: 13-10-22 * Time: 下午5:19 * To change this template use File | Settings | File Templates. */ public class ATest { public static void main(String args[]){ ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring-config.xml"); Animal animal=applicationContext.getBean("cat",Cat.class); animal.say(); animal.move(); Animal animal1=applicationContext.getBean("dog",Dog.class); animal1.say(); animal1.move(); Animal animal2=applicationContext.getBean("bird",Bird.class); animal2.say(); animal2.move(); } }
这突出了面向接口编程了。
总之还不错,看了一些,挺不错的。