Spring框架中<bean>第一种补充
原始方法:
main函数:
public static void learnCourse(){ student student=new student(); student.learnJava(); student.learnHtml(); } public static void main(String[] args){ learnCourse(); }
student类中加入:
public void learnJava(){ Icourse course=new JavaIcourse(); course.learn(); } public void learnHtml(){ Icourse course=new HtmlIcourse(); course.learn(); }
使用接口Icourse 用类JavaIcourse和HtmlIcourse进行继承,并重写learn函数
Icourse: public interface Icourse { void learn(); } JavaIcourse: public class JavaIcourse implements Icourse{ public void learn(){ System.out.println("学习java"); } } HtmlIcourse: public class HtmlIcourse implements Icourse{ public void learn(){ System.out.println("学习html"); } }
使用工厂模式:
改变的地方:
main函数:
public static void learnCourse(){ student student=new student(); student.learn("java"); } public static void main(String[] args){ learnCourse(); }
student类中:
public void learn(String name){ Icourse course=factory.getCourse(name); course.learn(); }
加入factory类(工厂模式):
public class factory { //根据名字获取课程的方法 public static Icourse getCourse(String name){ if(name.equals("java")){ return new JavaIcourse(); } else return new HtmlIcourse(); } }
将factory类去掉在bean中添加:
<bean id="JavaIcourse" class="org_shitang_instance.JavaIcourse"></bean> <bean id="HtmlIcourse" class="org_shitang_instance.HtmlIcourse"></bean>
在student类中修改:
public void learn(String name){ ApplicationContext conext=new ClassPathXmlApplicationContext("applicationContext.xml"); Icourse course=(Icourse)conext.getBean(name); course.learn(); }
main函数中:
public static void main(String[] args){ ApplicationContext conext=new ClassPathXmlApplicationContext("applicationContext.xml"); student student=(student)conext.getBean("student"); student.learn("Html"); }
相关推荐
与卿画眉共浮生 2020-11-13
smalllove 2020-11-03
hellowordmonkey 2020-11-02
丽丽 2020-10-30
周太郎 2020-10-28
greensomnuss 2020-10-27
职业炮灰 2020-10-16
与卿画眉共浮生 2020-10-14
feinifi 2020-10-14
feinifi 2020-10-13
yangjinpingc 2020-10-09
davis 2020-09-29
RickyIT 2020-09-27
lisongchuang 2020-09-27
tangxiong0 2020-09-03
meleto 2020-08-17
幸运小侯子 2020-08-14
YangHuiLiang 2020-08-06