标签:
首先,要用Eclipse开发Spring程序,需要安装Spring插件并重启Eclipse
具体操作:
新建java Project后,导入需要使用的包(提前下好Spring),Spring包包含6个部分的jar,我们只要导入用的即可
程序开发场景准备:
角色 -
执行动作的人群:proformer,接口
实现的类:Juggler,杂技师
发布指令的主类:Main
舞台准备:spring-idol.xml,配置bean,谁具备上场表现的机会
具体代码:
Proformer接口:
package com.springinaction.springidol; public interface Proformer { void perform() throws Exception; }
Juggler类:
package com.springinaction.springidol; public class Juggler implements Proformer { private int beanBags = 3; //默认杂技师可以抛3个豆子 public Juggler(){ } @Override public void perform() throws Exception { System.out.println("JUGGLING " + beanBags + " BEANBAGS"); } }
Main:
package com.springinaction.springidol; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "com/springinaction/springidol/spring-idol.xml"); Proformer performer = (Proformer)ctx.getBean("duke"); try { performer.perform(); } catch (Exception e) { e.printStackTrace(); } } }
spring-idol.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="duke" class="com.springinaction.springidol.Juggler" > </bean> </beans>
执行结果:JUGGLING 3 BEANBAGS
现在提要求了,组委会要搞比赛,杂技师一次抛3个豆子不能获得冠军,必须要能抛更多的豆子。我们修改下杂技师的能力(构造方法)
package com.springinaction.springidol;
public class Juggler implements Proformer {
private int beanBags = 3; //默认杂技师可以抛3个豆子
public Juggler(){
}
Juggler(int beanBags){ //增加一个构造方法,组委会提供多少豆子,杂技师都能玩得转
this.beanBags = beanBags;
}
@Override
public void perform() throws Exception {
System.out.println("JUGGLING " + beanBags + " BEANBAGS");
}
}
然后组委会可以要是提要求了,要求要在舞台准备中做:
修改spring-idol.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="duke" class="com.springinaction.springidol.Juggler" >
<constructor-arg value="15"></constructor-arg> <!-- 组委会说,抛15个豆子看看吧 -->
</bean>
</beans>
跑Main表演:JUGGLING 15 BEANBAGS,瓦萨,牛逼了!
标签:
原文地址:http://www.cnblogs.com/runwulingsheng/p/5622543.html